#!/usr/bin/env bash

if [ -z "$BIN_DIR" ] || [ -z "$INST_DIR" ] || [ -z "$MESH_HOME" ]; then
    echo "$0 is not intended to be run directly. Run stop-mesh.sh instead"
    exit 1
fi

PIDFILE="$MESH_HOME/log/mesh.pid"
if [ ! -f "$PIDFILE" ]; then
    echo "No PID file was found for Bitbucket Mesh"
    exit 0
fi
if [ ! -s "$PIDFILE" ]; then
    echo "The PID file for Bitbucket Mesh is empty"
    rm -f "$PIDFILE" >/dev/null 2>&1
    exit 1
fi

PID=$(cat "$PIDFILE")
kill -0 "$PID" >/dev/null 2>&1
if [ $? -gt 0 ]; then
    echo "No process was found for PID $PID, or the current user cannot signal it"
    exit 1
fi

echo -e "\nStopping Bitbucket Mesh"
kill "$PID"

SLEEP=${MESH_SHUTDOWN_TIMEOUT:-40}
while [ "$SLEEP" -ge 0 ]; do
    kill -0 "$PID" >/dev/null 2>&1
    if [ $? -gt 0 ]; then
        rm -f "$PIDFILE" >/dev/null 2>&1
        if [ $? != 0 ]; then
            echo "Warning: $PIDFILE could not be removed"
        fi
        echo "Bitbucket Mesh has stopped"
        exit 0
    fi

    if [ "$SLEEP" -gt 0 ]; then
        sleep 1
    elif [ "$SLEEP" -eq 0 ]; then
        echo "Bitbucket Mesh did not stop in time"

        kill -3 "$PID"
        if [ $? -eq 0 ]; then
            echo "Check $MESH_HOME/log/launcher.log for a thread dump"
        fi
    fi
    SLEEP=$((SLEEP - 1))
done

echo "Killing Bitbucket Mesh"
kill -9 "$PID"

KILL_SLEEP=5
while [ $KILL_SLEEP -ge 0 ]; do
    kill -0 "$PID" >/dev/null 2>&1
    if [ $? -gt 0 ]; then
        rm -f "$PIDFILE" >/dev/null 2>&1
        if [ $? -ne 0 ]; then
            echo "Warning: $PIDFILE could not be removed"
        fi
        echo "Bitbucket Mesh has been killed"
        break;
    fi

    if [ $KILL_SLEEP -gt 0 ]; then
        sleep 1;
    fi
    KILL_SLEEP=$((KILL_SLEEP - 1))
done

if [ $KILL_SLEEP -lt 0 ]; then
    echo "Bitbucket Mesh could not be killed. It may require administrator intervention"
fi