#!/bin/bash

LOGDIR="$HOME/winlink-launcher-logs"

timestamp() {
    date "+%Y-%m-%d %H:%M:%S"
}

log() {
    echo "[$(timestamp)] $*"
}

notify() {
    osascript -e "display notification \"$1\" with title \"Winlink ARDOP\"" \
        >/dev/null 2>&1
}

stop_process() {
    local name="$1"
    local pattern="$2"

    if pgrep -f "$pattern" >/dev/null 2>&1; then
        log "Stopping $name..."
        pkill -TERM -f "$pattern"

        for i in {1..10}; do
            if ! pgrep -f "$pattern" >/dev/null 2>&1; then
                log "$name stopped."
                return 0
            fi
            sleep 0.5
        done

        log "$name did not stop normally; forcing shutdown."
        pkill -KILL -f "$pattern" >/dev/null 2>&1
    else
        log "$name is not running."
    fi
}

echo
echo "============================================================"
echo "             VE3ZDN WINLINK / ARDOP SHUTDOWN"
echo "============================================================"
echo

# Reverse startup order.

stop_process "Pat" '(^|/)pat( |$).*http'
stop_process "ardopcf" 'ardopcf'
stop_process "rigctld" 'rigctld'

stop_process "gpsd" 'gpsd.*2947'
stop_process "Core Location NMEA feed" 'corelocation-nmea'
stop_process "GPS socat bridge" 'socat.*corelocation-gps'

rm -f "$HOME/corelocation-gps" "$HOME/corelocation-gps-feed"

echo
echo "============================================================"
echo "                  STATION SHUT DOWN"
echo "============================================================"
echo

notify "Winlink ARDOP station shut down"

exit 0
