#!/bin/bash
set -euo pipefail

PLIST="$HOME/Library/LaunchAgents/com.hungryroot.django.plist"
ICON="🔌"
MATCH="&& just django"

LABEL="$(/usr/bin/plutil -extract Label raw -o - "$PLIST" 2>/dev/null || true)"
UID_NUM="$(/usr/bin/id -u)"
DOMAIN="gui/$UID_NUM"
TARGET="$DOMAIN/$LABEL"

is_running() {
    /bin/ps waux | /usr/bin/grep -F "$MATCH" | /usr/bin/grep -v grep >/dev/null 2>&1
}

pids() {
    /bin/ps waux | /usr/bin/grep -F "$MATCH" | /usr/bin/grep -v grep | /usr/bin/awk '{print $2}'
}

# --- Title ---
if is_running; then
    echo "$ICON 🟢"
else
    echo "$ICON 🔴"
fi

echo "---"

if is_running; then
    echo "Stop | bash='$0' param1=stop terminal=false refresh=true"
    echo "Restart | bash='$0' param1=restart terminal=false refresh=true"
else
    echo "Start | bash='$0' param1=start terminal=false refresh=true"
fi

echo "---"
echo "Open http://0.0.0.0:9000 | href=http://0.0.0.0:9000"
echo "Debug | bash='$0' param1=debug terminal=true"
echo "Open plist | bash='/usr/bin/open' param1='$PLIST' terminal=false"

ACTION="${1:-}"
case "$ACTION" in
start)
    [[ -n "${LABEL:-}" ]] || {
        echo "ERROR: couldn't read Label from $PLIST" >&2
        exit 1
    }
    /bin/launchctl bootstrap "$DOMAIN" "$PLIST" 2>/dev/null || true
    /bin/launchctl kickstart -k "$TARGET" 2>/dev/null || true
    ;;
stop)
    # THIS is the important part: unload the LaunchAgent so it won’t restart.
    [[ -n "${LABEL:-}" ]] || exit 0
    /bin/launchctl bootout "$TARGET" 2>/dev/null || true

    # Optional cleanup: kill any remaining process that matches
    pids | /usr/bin/xargs -r kill -TERM 2>/dev/null || true
    ;;
restart)
    "$0" stop
    sleep 0.5
    "$0" start
    ;;
debug)
    echo "PLIST: $PLIST"
    echo "LABEL: $LABEL"
    echo "TARGET: $TARGET"
    echo
    echo "=== launchctl print (may fail in SwiftBar, still useful) ==="
    /bin/launchctl print "$TARGET" 2>&1 || true
    echo
    echo "=== matching processes ==="
    /bin/ps waux | /usr/bin/grep -F "$MATCH" | /usr/bin/grep -v grep || echo "(no matches)"
    ;;
esac
