#!/bin/bash
set -eu
: "${TRIM_APPDEST:?}" "${TRIM_PKGVAR:?}"
PID_FILE="${TRIM_PKGVAR}/strm.pid"
SERVER="$(readlink -f "${TRIM_APPDEST}/server/leelaa-strm")"
SOCKET="${TRIM_APPDEST}/leelaa-strm.sock"
DATA_DIR="${TRIM_DATA_SHARE_PATHS:-}"
DATA_DIR="${DATA_DIR%%:*}"
DATA_DIR="${DATA_DIR:-${TRIM_PKGVAR}/data}"
LOG_FILE="${TRIM_PKGVAR}/strm.log"
mkdir -p "$TRIM_PKGVAR"
exec 9>"${TRIM_PKGVAR}/lifecycle.lock"
flock -x 9
is_running() {
    [ -r "$PID_FILE" ] || return 1
    pid=$(cat "$PID_FILE")
    case "$pid" in ''|*[!0-9]*) return 1 ;; esac
    [ "$pid" -gt 1 ] && kill -0 "$pid" 2>/dev/null && [ "$(readlink "/proc/$pid/exe" 2>/dev/null)" = "$SERVER" ]
}
instance_pids() {
    for proc in /proc/[0-9]*/exe; do
        executable=$(readlink "$proc" 2>/dev/null) || continue
        case "$executable" in
            "$SERVER"|"$SERVER (deleted)")
                candidate=${proc#/proc/}; printf '%s\n' "${candidate%/exe}"
                ;;
        esac
    done
}
cleanup_owned_start() {
    # Clean up only the process created by this start invocation.
    if [ -n "${owned_pid:-}" ] && [ "$(readlink "/proc/$owned_pid/exe" 2>/dev/null || true)" = "$SERVER" ]; then
        kill -TERM "$owned_pid" 2>/dev/null || true
        for attempt in $(seq 1 10); do
            kill -0 "$owned_pid" 2>/dev/null || break
            sleep 1
        done
        if [ "$(readlink "/proc/$owned_pid/exe" 2>/dev/null || true)" = "$SERVER" ]; then kill -KILL "$owned_pid" 2>/dev/null || true; fi
        wait "$owned_pid" 2>/dev/null || true
    fi
    if [ "$(cat "$PID_FILE" 2>/dev/null || true)" = "${owned_pid:-}" ]; then rm -f "$PID_FILE" "$SOCKET"; fi
}
healthy() {
    command -v curl >/dev/null 2>&1 && [ -S "$SOCKET" ] &&
        curl -fsS --max-time 2 --unix-socket "$SOCKET" http://localhost/health >/dev/null &&
        curl -fsS --max-time 2 --unix-socket "$SOCKET" http://localhost/ >/dev/null
}
stop_instances() {
    for candidate in $(instance_pids); do kill -TERM "$candidate" 2>/dev/null || true; done
    for attempt in $(seq 1 10); do
        [ -n "$(instance_pids)" ] || return 0
        sleep 1
    done
    for candidate in $(instance_pids); do kill -KILL "$candidate" 2>/dev/null || true; done
    [ -z "$(instance_pids)" ]
}
case "${1:-}" in
start)
    if is_running; then healthy && exit 0; fi
    command -v curl >/dev/null 2>&1 || exit 1
    [ -x "$SERVER" ] && [ -f "${TRIM_APPDEST}/ui/index.html" ] || exit 1
    stop_instances
    mkdir -p "$DATA_DIR" "$TRIM_PKGVAR/keys"
    chmod 700 "$TRIM_PKGVAR/keys"
    rm -f "$SOCKET" "$PID_FILE"
    if [ -f "$LOG_FILE" ] && [ "$(wc -c < "$LOG_FILE")" -gt 10485760 ]; then mv -f "$LOG_FILE" "${LOG_FILE}.1"; fi
    export STRM_MODE=fnos
    export LEELAA_STRM_DATA_DIR="$DATA_DIR"
    export LEELAA_STRM_FRONTEND_DIR="${TRIM_APPDEST}/ui"
    export FNNAS_GATEWAY_SOCKET="$SOCKET" FNNAS_GATEWAY_PREFIX=/app/leelaa-strm
    export RUST_LOG=info
    "$SERVER" 9>&- >> "$LOG_FILE" 2>&1 &
    owned_pid=$!
    echo "$owned_pid" > "$PID_FILE"
    trap cleanup_owned_start EXIT
    trap 'exit 1' HUP INT TERM
    for attempt in $(seq 1 15); do
        is_running || exit 1
        if healthy; then trap - EXIT HUP INT TERM; exit 0; fi
        sleep 1
    done
    exit 1
    ;;
stop)
    stop_instances
    rm -f "$PID_FILE" "$SOCKET"
    ;;
status)
    if is_running; then healthy && exit 0; fi
    exit 3
    ;;
*) exit 1 ;;
esac
