#!/bin/bash
# scorpiox-apps-supervisor: Run and supervise multiple native C scorpiox-server
# sites behind an internal Caddy ingress inside a single Debian-slim container.
#
# Manifest format (APPS_MANIFEST, default /etc/scorpiox-apps/sites.conf):
#   <domain>|<port>|<git_repo_url>[|<branch>]
# Blank lines and '#' comments are ignored.
#
# Environment variables:
#   APPS_MANIFEST      Path to sites.conf (default: /etc/scorpiox-apps/sites.conf)
#   APPS_INGRESS_PORT  Caddy HTTP listen port (default: 8300)
#   APPS_CACHE_DIR     Git clone cache dir (default: /var/cache/scorpiox-apps)
#   APPS_POLL_SECS     Git poll interval in seconds (default: 10)
#   APPS_LOG_DIR       Log directory (default: /var/log/scorpiox-apps)
#   APPS_RUN_DIR       Runtime dir for generated Caddyfile (default: /run/scorpiox-apps)
#   SERVER_GIT_PAT     Optional git PAT inherited by scorpiox-server via env

set -u

APPS_MANIFEST="${APPS_MANIFEST:-/etc/scorpiox-apps/sites.conf}"
APPS_INGRESS_PORT="${APPS_INGRESS_PORT:-8300}"
APPS_CACHE_DIR="${APPS_CACHE_DIR:-/var/cache/scorpiox-apps}"
APPS_POLL_SECS="${APPS_POLL_SECS:-10}"
APPS_LOG_DIR="${APPS_LOG_DIR:-/var/log/scorpiox-apps}"
APPS_RUN_DIR="${APPS_RUN_DIR:-/run/scorpiox-apps}"

log() {
    printf '[%s] [apps-supervisor] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" >&2
}

usage() {
    cat <<'EOF'
scorpiox-apps-supervisor - Multi-site scorpiox-server + Caddy supervisor

Usage:
  scorpiox-apps-supervisor              Start supervisor from APPS_MANIFEST
  scorpiox-apps-supervisor --self-test  Verify binaries, manifest parser, and Caddyfile generation
  scorpiox-apps-supervisor --help       Show this help

Manifest (/etc/scorpiox-apps/sites.conf):
  <domain>|<port>|<git_repo_url>[|<branch>]
EOF
}

trim() {
    local s="$1"
    s="${s//$'\r'/}"
    s="${s#"${s%%[![:space:]]*}"}"
    s="${s%"${s##*[![:space:]]}"}"
    printf '%s' "$s"
}

# Populates global arrays: SITE_DOMAINS, SITE_PORTS, SITE_REPOS, SITE_BRANCHES
parse_manifest() {
    local manifest_file="$1"
    SITE_DOMAINS=()
    SITE_PORTS=()
    SITE_REPOS=()
    SITE_BRANCHES=()

    if [ ! -f "$manifest_file" ]; then
        log "ERROR: manifest file not found: $manifest_file"
        return 1
    fi

    local seen_ports=" "
    local seen_domains=" "
    local lineno=0
    local line domain port repo branch extra

    while IFS= read -r line || [ -n "$line" ]; do
        lineno=$((lineno + 1))
        line="$(trim "$line")"
        [ -z "$line" ] && continue
        case "$line" in
            \#*) continue ;;
        esac

        IFS='|' read -r domain port repo branch extra <<< "$line"
        domain="$(trim "${domain:-}")"
        port="$(trim "${port:-}")"
        repo="$(trim "${repo:-}")"
        branch="$(trim "${branch:-}")"
        [ -z "$branch" ] && branch="main"

        if [ -z "$domain" ] || [ -z "$port" ] || [ -z "$repo" ]; then
            log "ERROR: invalid manifest entry at ${manifest_file}:${lineno}: '$line'"
            return 1
        fi
        case "$port" in
            *[!0-9]*|'')
                log "ERROR: invalid port '$port' at ${manifest_file}:${lineno}"
                return 1
                ;;
        esac
        if [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then
            log "ERROR: port out of range '$port' at ${manifest_file}:${lineno}"
            return 1
        fi
        case "$seen_ports" in
            *" $port "*)
                log "ERROR: duplicate port '$port' at ${manifest_file}:${lineno}"
                return 1
                ;;
        esac
        case "$seen_domains" in
            *" $domain "*)
                log "ERROR: duplicate domain '$domain' at ${manifest_file}:${lineno}"
                return 1
                ;;
        esac

        seen_ports="${seen_ports}${port} "
        seen_domains="${seen_domains}${domain} "
        SITE_DOMAINS+=("$domain")
        SITE_PORTS+=("$port")
        SITE_REPOS+=("$repo")
        SITE_BRANCHES+=("$branch")
    done < "$manifest_file"

    if [ "${#SITE_DOMAINS[@]}" -eq 0 ]; then
        log "ERROR: manifest contains zero active sites: $manifest_file"
        return 1
    fi
    return 0
}

generate_caddyfile() {
    local out_file="$1"
    local ingress_port="$2"
    local i

    {
        printf '{\n'
        printf '\tadmin off\n'
        printf '\tauto_https off\n'
        printf '}\n\n'
        for i in "${!SITE_DOMAINS[@]}"; do
            printf 'http://%s:%s {\n' "${SITE_DOMAINS[$i]}" "$ingress_port"
            printf '\treverse_proxy 127.0.0.1:%s\n' "${SITE_PORTS[$i]}"
            printf '}\n\n'
        done
        printf 'http://:%s {\n' "$ingress_port"
        printf '\trespond /healthz "ok" 200\n'
        printf '\trespond 404\n'
        printf '}\n'
    } > "$out_file"
}

run_self_test() {
    local bin tmp_dir tmp_manifest tmp_caddy
    for bin in bash git curl caddy scorpiox-server; do
        if ! command -v "$bin" >/dev/null 2>&1; then
            log "FAIL: missing required binary: $bin"
            return 1
        fi
    done

    if ! scorpiox-server --help >/dev/null 2>&1; then
        log "FAIL: scorpiox-server --help exited non-zero"
        return 1
    fi

    tmp_dir="$(mktemp -d)"
    tmp_manifest="${tmp_dir}/sites.conf"
    tmp_caddy="${tmp_dir}/Caddyfile"

    cat > "$tmp_manifest" <<'EOF'
# sample manifest for self-test
example.scorpiox.net|18081|https://appsgit.scorpiox.net/scorpiox-native-c-app-example-landing-website.git|main
second.scorpiox.net|18082|https://appsgit.scorpiox.net/scorpiox-native-c-app-second-landing-website.git
EOF

    if ! parse_manifest "$tmp_manifest"; then
        rm -rf "$tmp_dir"
        log "FAIL: parse_manifest failed on sample manifest"
        return 1
    fi
    if [ "${#SITE_DOMAINS[@]}" -ne 2 ]; then
        rm -rf "$tmp_dir"
        log "FAIL: expected 2 parsed sites, got ${#SITE_DOMAINS[@]}"
        return 1
    fi

    generate_caddyfile "$tmp_caddy" "$APPS_INGRESS_PORT"
    if ! caddy validate --config "$tmp_caddy" --adapter caddyfile >/dev/null 2>&1; then
        caddy validate --config "$tmp_caddy" --adapter caddyfile || true
        rm -rf "$tmp_dir"
        log "FAIL: caddy validate failed"
        return 1
    fi

    rm -rf "$tmp_dir"
    printf '[apps-supervisor] self-test OK (sites=%d, ingress_port=%s, caddy=%s)\n' \
        "${#SITE_DOMAINS[@]}" "$APPS_INGRESS_PORT" "$(caddy version | head -n 1)"
    return 0
}

case "${1:-}" in
    --self-test)
        run_self_test
        exit $?
        ;;
    --help|-h)
        usage
        exit 0
        ;;
    "")
        ;;
    *)
        log "ERROR: unknown argument: $1"
        usage
        exit 1
        ;;
esac

mkdir -p "$APPS_CACHE_DIR" "$APPS_LOG_DIR" "$APPS_RUN_DIR"

if ! parse_manifest "$APPS_MANIFEST"; then
    exit 1
fi

CADDYFILE="${APPS_RUN_DIR}/Caddyfile"
generate_caddyfile "$CADDYFILE" "$APPS_INGRESS_PORT"
if ! caddy validate --config "$CADDYFILE" --adapter caddyfile >/dev/null 2>&1; then
    log "ERROR: generated Caddyfile failed validation: $CADDYFILE"
    caddy validate --config "$CADDYFILE" --adapter caddyfile >&2 || true
    exit 1
fi

if [ -n "${SERVER_GIT_PAT:-}" ]; then
    export SERVER_GIT_PAT
fi

SITE_PIDS=()
CADDY_PID=""
STOPPING=0

start_site() {
    local idx="$1"
    local domain="${SITE_DOMAINS[$idx]}"
    local port="${SITE_PORTS[$idx]}"
    local repo="${SITE_REPOS[$idx]}"
    local branch="${SITE_BRANCHES[$idx]}"
    local logfile="${APPS_LOG_DIR}/${domain}.log"

    scorpiox-server \
        -r "$repo" \
        -b "$branch" \
        -p "$port" \
        --poll "$APPS_POLL_SECS" \
        -e SERVER_ROUTE_PREFIX=/ \
        -e SERVER_GIT_CACHE_DIR="$APPS_CACHE_DIR" \
        -e SERVER_QUERY_STRING=raw \
        >> "$logfile" 2>&1 &
    SITE_PIDS[$idx]=$!
    log "started $domain (port=$port branch=$branch pid=${SITE_PIDS[$idx]})"
}

start_caddy() {
    caddy run --config "$CADDYFILE" --adapter caddyfile >> "${APPS_LOG_DIR}/caddy.log" 2>&1 &
    CADDY_PID=$!
    log "started caddy ingress on :${APPS_INGRESS_PORT} (pid=${CADDY_PID}, sites=${#SITE_DOMAINS[@]})"
}

cleanup() {
    STOPPING=1
    log "shutting down children..."
    local pid
    if [ -n "$CADDY_PID" ] && kill -0 "$CADDY_PID" 2>/dev/null; then
        kill -TERM "$CADDY_PID" 2>/dev/null || true
    fi
    for pid in "${SITE_PIDS[@]}"; do
        if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
            kill -TERM "$pid" 2>/dev/null || true
        fi
    done

    local deadline=$((SECONDS + 5))
    while [ "$SECONDS" -lt "$deadline" ]; do
        local alive=0
        if [ -n "$CADDY_PID" ] && kill -0 "$CADDY_PID" 2>/dev/null; then
            alive=1
        fi
        for pid in "${SITE_PIDS[@]}"; do
            if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
                alive=1
            fi
        done
        [ "$alive" -eq 0 ] && break
        sleep 0.2
    done

    if [ -n "$CADDY_PID" ] && kill -0 "$CADDY_PID" 2>/dev/null; then
        kill -KILL "$CADDY_PID" 2>/dev/null || true
    fi
    for pid in "${SITE_PIDS[@]}"; do
        if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
            kill -KILL "$pid" 2>/dev/null || true
        fi
    done
    wait >/dev/null 2>&1 || true
    log "shutdown complete"
    exit 0
}

trap cleanup SIGTERM SIGINT SIGQUIT SIGHUP

for i in "${!SITE_DOMAINS[@]}"; do
    start_site "$i"
done
start_caddy

# Verify Caddy survived initial startup
sleep 1 &
wait $! || true
if [ "$STOPPING" -eq 0 ] && ! kill -0 "$CADDY_PID" 2>/dev/null; then
    log "ERROR: caddy exited immediately on startup (see ${APPS_LOG_DIR}/caddy.log)"
    tail -n 20 "${APPS_LOG_DIR}/caddy.log" >&2 || true
    STOPPING=1
    for pid in "${SITE_PIDS[@]}"; do
        kill -TERM "$pid" 2>/dev/null || true
    done
    wait >/dev/null 2>&1 || true
    exit 1
fi

while [ "$STOPPING" -eq 0 ]; do
    sleep 3 &
    wait $! || true
    [ "$STOPPING" -ne 0 ] && break

    if ! kill -0 "$CADDY_PID" 2>/dev/null; then
        wait "$CADDY_PID" 2>/dev/null || true
        log "WARN: caddy died, restarting..."
        sleep 2 &
        wait $! || true
        [ "$STOPPING" -ne 0 ] && break
        start_caddy
    fi

    for i in "${!SITE_DOMAINS[@]}"; do
        pid="${SITE_PIDS[$i]}"
        if ! kill -0 "$pid" 2>/dev/null; then
            wait "$pid" 2>/dev/null || true
            log "WARN: ${SITE_DOMAINS[$i]} (pid=$pid) died, restarting..."
            sleep 1 &
            wait $! || true
            [ "$STOPPING" -ne 0 ] && break
            start_site "$i"
        fi
    done
done
