#!/usr/bin/env bash
# TO MANUALLY KILL TAGUI PROCESSES, EG IF CTRL+C WAS USED TO QUIT TAGUI ~ TEBEL.ORG #

# aggressive failsafe for tagui and friends that have not exited gracefully
# works by scanning processes for tagui keywords and killing them one by one

while true; do
    php_process_id="$(ps x | grep tagui_chrome\.php | grep -v 'grep tagui_chrome\.php' | sed -e 's/^[ ]*//' | cut -d' ' -f 1 | sort -nur | head -n 1)"
    if [ -n "$php_process_id" ]; then
        kill $php_process_id > /dev/null 2>&1
    else
        break
    fi
done

while true; do
    chrome_process_id="$(ps x | grep remote-debugging-port=9222 | grep tagui_user_profile | grep window-size | sed -e 's/^[ ]*//' | cut -d' ' -f 1 | sort -nur | head -n 1)"
    if [ -n "$chrome_process_id" ]; then
        kill $chrome_process_id > /dev/null 2>&1
    else
        break
    fi
done

while true; do
    sikuli_process_id="$(ps x | grep tagui\.sikuli | grep -v 'grep tagui\.sikuli' | sed -e 's/^[ ]*//' | cut -d' ' -f 1 | sort -nur | head -n 1)"
    if [ -n "$sikuli_process_id" ]; then
        kill $sikuli_process_id > /dev/null 2>&1
    else
        break
    fi
done

while true; do
    python_process_id="$(ps x | grep tagui_py\.py | grep -v 'grep tagui_py\.py' | sed -e 's/^[ ]*//' | cut -d' ' -f 1 | sort -nur | head -n 1)"
    if [ -n "$python_process_id" ]; then
        kill $python_process_id > /dev/null 2>&1
    else
        break
    fi
done

while true; do
    r_process_id="$(ps x | grep tagui_r\.R | grep -v 'grep tagui_r\.R' | sed -e 's/^[ ]*//' | cut -d' ' -f 1 | sort -nur | head -n 1)"
    if [ -n "$r_process_id" ]; then
        kill $r_process_id > /dev/null 2>&1
    else
        break
    fi
done

# get END_PROCESSES directory to create end_processes_signal to quit datatable loops
SOURCE="${BASH_SOURCE[0]}" # slimerjs's implementation instead of cd "`dirname "$0"`"
while [ -h "$SOURCE" ]; do END_PROCESSES_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$(readlink "$SOURCE")"; [[ $SOURCE != /* ]] && SOURCE="$END_PROCESSES_DIR/$SOURCE"; done
END_PROCESSES_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"; e_p_signal=false

while true; do
    tagui_process_id="$(ps x | grep tagui/src/ | grep -v 'grep tagui/src/' | grep -v 'end_processes' | sed -e 's/^[ ]*//' | cut -d' ' -f 1 | sort -nur | head -n 1)"
    if [ -n "$tagui_process_id" ]; then
        if [ "$e_p_signal" == false ]; then e_p_signal=true; touch "$END_PROCESSES_DIR/end_processes_signal"; fi
        kill $tagui_process_id > /dev/null 2>&1
    else
        break
    fi
done
