#!/bin/bash
# Stop the gui and back-end in any case

. /etc/odemis.conf
RUN_DIR="/var/run/odemisd"

export PYTHONPATH

GRACE_PER_COMP=5  # s

# Clean up the run directory that contains pipes for connection between backend and clients
clean_run_dir () {
    if [ -e "$RUN_DIR" ]; then
        # try only if there is something worthy to delete (ie, dir is not empty)
        if ! find "$RUN_DIR" -maxdepth 0 -empty | read v; then
            echo "Cleaning $RUN_DIR"
            rm -rf "$RUN_DIR"/*
        fi
    fi
}

# kill the GUI if it's already there
if pgrep -f $GUI > /dev/null; then
    echo "Stopping the GUI"
    pkill -f $GUI
fi


# Stop the backend
#BEP_PID=$(pgrep odemisd) # parent PID
OLD_BE_PIDS=$(pgrep -f $BACKEND)
if [ -n "$OLD_BE_PIDS" ]; then
    # try nicely
    echo "Stopping the back-end"
    odemis-cli --kill
    # Only kill the old processes, so that if the user has started a new
    # instance in the mean time, it doesn't get killed
    NLEFT_PIDS=$(wc -w <<< "$OLD_BE_PIDS")
    NOLD_PIDS=$(($NLEFT_PIDS + 1)) # To force it to enter the while block on the first time

    # As long as number of PIDS decreases, sleep more
    while [ "$NLEFT_PIDS" -gt 0 -a "$NLEFT_PIDS" -lt "$NOLD_PIDS" ]; do
        echo "Waiting for the back-end ($NLEFT_PIDS processes left)..."
        sleep $GRACE_PER_COMP
        NOLD_PIDS="$NLEFT_PIDS"
        NOW_BE_PIDS=$(pgrep -f $BACKEND)
        LEFT_BE_PIDS=$(sort <<< "$OLD_BE_PIDS"$'\n'"$NOW_BE_PIDS" | uniq -d | sed '/^ $/d')
        NLEFT_PIDS=$(wc -w <<< "$LEFT_BE_PIDS")
    done
    #echo "Left = $LEFT_BE_PIDS"
    if [ -n "$LEFT_BE_PIDS" ]; then
        echo "Back-end still running ($LEFT_BE_PIDS processes), killing it..."
        # TODO: don't use sudo and fail if the backend is running as root and not this script
        sudo /bin/kill $LEFT_BE_PIDS
#        sudo /bin/kill $BEP_PID

        sleep $GRACE_PER_COMP
        # Try even harder
        if pgrep -f $BACKEND > /dev/null; then
            echo "Back-end is apparently dead, trying harder to kill it..."
#            sudo pkill -CONT -P $BEP_PID,${BE_PIDS//$'\n'/,} -f $BACKEND
            sudo /bin/kill -CONT $LEFT_BE_PIDS # in case it was STOPPED
            sudo /bin/kill -KILL $LEFT_BE_PIDS
        fi
        clean_run_dir
    fi
else
    # No odemis backend found?
    # The user probably asked for some reason, so at least clean up the run dir
    clean_run_dir
fi


