#!/bin/bash
set -euo pipefail

ICON="🐳"
PROJECT_DIR="$HOME/src/github.com/hungryroot/hungryroot"
JUST_CMD="docker-run"

# Containers that belong to this stack (from your docker ps)
STACK_CONTAINERS=("mysql" "nginx" "redis")

# Paths (SwiftBar PATH can be limited)
DOCKER="/opt/homebrew/bin/docker"
[[ -x "$DOCKER" ]] || DOCKER="/usr/local/bin/docker"
JUST="/opt/homebrew/bin/just"
[[ -x "$JUST" ]] || JUST="/usr/local/bin/just"
command -v docker >/dev/null 2>&1 && DOCKER="$(command -v docker)" || true
command -v just >/dev/null 2>&1 && JUST="$(command -v just)" || true

docker_ok() {
    "$DOCKER" info >/dev/null 2>&1
}

any_running() {
    local name
    for name in "${STACK_CONTAINERS[@]}"; do
        if "$DOCKER" ps --format '{{.Names}}' 2>/dev/null | /usr/bin/grep -Fxq "$name"; then
            return 0
        fi
    done
    return 1
}

running_list() {
    local name out=()
    for name in "${STACK_CONTAINERS[@]}"; do
        if "$DOCKER" ps --format '{{.Names}}' 2>/dev/null | /usr/bin/grep -Fxq "$name"; then
            out+=("$name")
        fi
    done
    printf "%s\n" "${out[@]:-}"
}

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

echo "---"

echo "Open http://127.0.0.1:8000 | href=http://127.0.0.1:8000"
echo "Run: just $JUST_CMD | bash='$0' param1=up terminal=true refresh=true"
echo "Stop Hungryroot stack (mysql/nginx/redis) | bash='$0' param1=down terminal=true refresh=true"
echo "---"
echo "docker ps (filtered) | bash='$0' param1=ps terminal=true"
echo "Open project dir | bash='/usr/bin/open' param1='$PROJECT_DIR' terminal=false"

ACTION="${1:-}"
case "$ACTION" in
up)
    echo "== Checking Docker =="
    if ! docker_ok; then
        echo "Docker engine not reachable."
        echo "If you use Colima: run 'colima start' first."
        exit 1
    fi
    echo "OK ✅"
    echo
    echo "== Running: just $JUST_CMD =="
    cd "$PROJECT_DIR"
    "$JUST" "$JUST_CMD"
    ;;
down)
    echo "== Stopping Hungryroot stack containers =="
    if ! docker_ok; then
        echo "Docker engine not reachable."
        exit 1
    fi

    RUNNING="$(running_list || true)"
    if [[ -z "${RUNNING:-}" ]]; then
        echo "(none of mysql/nginx/redis are running)"
        exit 0
    fi

    echo "$RUNNING" | /usr/bin/xargs -n 10 "$DOCKER" stop
    echo "Done ✅"
    ;;
ps)
    if ! docker_ok; then
        echo "Docker engine not reachable."
        exit 1
    fi
    echo "== Running (stack) =="
    running_list || true
    echo
    echo "== docker ps =="
    "$DOCKER" ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}' |
        /usr/bin/grep -E '^(NAMES|mysql|nginx|redis)\b' || true
    ;;
esac
