#!/bin/bash
set -euo pipefail

# --- CONFIG ---
MATCH="celery -A"
PLIST="$HOME/Library/LaunchAgents/com.hungryroot.celery.plist"
ICON="🥕"

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

# --- Menu bar title ---
if is_running; then
    echo "$ICON 🟢"
else
    echo "$ICON 🔴"
fi

echo "---"

# --- Actions ---
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 "Show matching processes | bash='$0' param1=ps terminal=true"
echo "Open plist | bash='/usr/bin/open' param1='$PLIST' terminal=false"

# --- Handler ---
ACTION="${1:-}"
case "$ACTION" in
start)
    /bin/launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/dev/null || true
    /bin/launchctl kickstart -k "gui/$(id -u)/$(/usr/bin/plutil -extract Label raw -o - "$PLIST")" 2>/dev/null || true
    ;;
stop)
    # Kill only matching Celery runserver processes
    /bin/ps waux | /usr/bin/grep -F "$MATCH" | /usr/bin/grep -v grep | /usr/bin/awk '{print $2}' | /usr/bin/xargs -r kill
    ;;
restart)
    "$0" stop
    sleep 0.5
    "$0" start
    ;;
ps)
    /bin/ps waux | /usr/bin/grep -F "$MATCH" | /usr/bin/grep -v grep || echo "(no matches)"
    ;;
esac
