#!/usr/bin/env bash
set -euo pipefail

ACTION="${1:-restart}"
PORT="${2:-3000}"
HOST="${3:-127.0.0.1}"

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
PIDFILE="$ROOT/.vscode/.phpserver-${PORT}.pid"
LOGFILE="$ROOT/.vscode/.phpserver-${PORT}.log"
PHP_BIN="/usr/bin/php"
PHP_INI="/etc/php/7.4/cli/php.ini"

get_port_pids() {
    ss -ltnp 2>/dev/null \
      | sed -n "s/.*:${PORT} .*users:((\"php\",pid=\([0-9]\+\).*/\1/p" \
      | sort -u
}

stop_server() {
    local pids=""

    if [[ -f "$PIDFILE" ]]; then
        local pid
        pid="$(cat "$PIDFILE" 2>/dev/null || true)"
        if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
            echo "Stopping pid from pidfile: $pid"
            kill "$pid" 2>/dev/null || true
            sleep 0.5
        fi
    fi

    pids="$(get_port_pids || true)"
    if [[ -n "$pids" ]]; then
        echo "Stopping php pids on :$PORT -> $(echo "$pids" | tr '\n' ' ')"
        while IFS= read -r p; do
            [[ -z "$p" ]] && continue
            kill "$p" 2>/dev/null || true
        done <<< "$pids"
        sleep 0.5
    fi

    rm -f "$PIDFILE"
}

start_server() {
    cd "$ROOT"

    echo "Starting PHP server: http://${HOST}:${PORT} (docroot: ${ROOT})"
    nohup "$PHP_BIN" -c "$PHP_INI" -S "${HOST}:${PORT}" -t "$ROOT" >> "$LOGFILE" 2>&1 &
    local pid=$!
    echo "$pid" > "$PIDFILE"

    sleep 0.7

    if kill -0 "$pid" 2>/dev/null; then
        echo "Started pid: $pid"
    else
        echo "Failed to start server. Check log: $LOGFILE"
        exit 1
    fi

    if command -v curl >/dev/null 2>&1; then
        if curl -fsS --max-time 3 "http://${HOST}:${PORT}/index.php" >/dev/null; then
            echo "Health check: OK (/index.php)"
        else
            echo "Health check: WARN (could not fetch /index.php quickly). See $LOGFILE"
        fi
    fi
}

status_server() {
    local pids
    pids="$(get_port_pids || true)"
    if [[ -n "$pids" ]]; then
        echo "RUNNING on :$PORT (php pid): $(echo "$pids" | tr '\n' ' ')"
        echo "Log: $LOGFILE"
        exit 0
    fi

    echo "STOPPED on :$PORT"
    exit 1
}

case "$ACTION" in
    restart)
        stop_server
        start_server
        ;;
    start)
        start_server
        ;;
    stop)
        stop_server
        echo "Stopped"
        ;;
    status)
        status_server
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status} [port] [host]"
        exit 2
        ;;
esac
