#!/usr/bin/env bash

APP="/opt/g6glp-contest-logger/G6GLPContestLogger"
PIDS=$(pgrep -f "^${APP//./\\.}$" || true)

if [ -z "$PIDS" ]; then
    echo "G6GLP Contest Logger is not running."
    read -r -p "Press Enter to close..."
    exit 0
fi

kill $PIDS

for attempt in $(seq 1 5); do
    sleep 1
    if ! pgrep -f "^${APP//./\\.}$" >/dev/null; then
        echo "G6GLP Contest Logger has been stopped."
        read -r -p "Press Enter to close..."
        exit 0
    fi
done

echo "The logger is still running. Trying a force stop..."
PIDS=$(pgrep -f "^${APP//./\\.}$" || true)
if [ -n "$PIDS" ]; then
    kill -9 $PIDS 2>/dev/null || true
fi

sleep 1

if pgrep -f "^${APP//./\\.}$" >/dev/null; then
    echo "Unable to stop the logger."
else
    echo "G6GLP Contest Logger has been stopped."
fi

read -r -p "Press Enter to close..."