#!/bin/bash
set -eu
: "${TRIM_APPDEST:?}" "${TRIM_PKGVAR:?}"
PID_FILE="${TRIM_PKGVAR}/drama.pid"
PORT_FILE="${TRIM_PKGVAR}/app-port"
SERVER="$(readlink -f "${TRIM_APPDEST}/server/leelaa-drama")"
SOCKET="${TRIM_APPDEST}/leelaa-drama.sock"
DATA_DIR="${TRIM_DATA_SHARE_PATHS:-}"
DATA_DIR="${DATA_DIR%%:*}"
DATA_DIR="${DATA_DIR:-${TRIM_PKGVAR}/data}"
LOG_FILE="${TRIM_PKGVAR}/drama.log"
TEMP_LOG="${TRIM_TEMP_LOGFILE:-}"
# Serialize control commands separately from the service's data-directory lock.
# The child must close fd 9 so it cannot retain this control lock after startup.
START_TIMEOUT="${DRAMA_START_TIMEOUT_SECONDS:-30}"
case "$START_TIMEOUT" in ''|*[!0-9]*) exit 1 ;; esac
[ "$START_TIMEOUT" -ge 1 ] && [ "$START_TIMEOUT" -le 120 ] || exit 1
export ACTIVATION_LEGACY_LICENSE_CUTOFF_UNIX=1794727548
export ACTIVATION_LEGACY_TRIAL_CUTOFF_UNIX=1794727548

report() {
    local message="$1"
    printf '%s\n' "$message" >&2
    if [ -n "$TEMP_LOG" ]; then
        printf '%s\n' "$message" >> "$TEMP_LOG" 2>/dev/null || true
    fi
}

service_pid() {
    local candidate="$1" executable first_arg second_arg
    case "$candidate" in ''|*[!0-9]*) return 1 ;; esac
    [ "$candidate" -gt 1 ] && kill -0 "$candidate" 2>/dev/null || return 1
    executable=$(readlink "/proc/$candidate/exe" 2>/dev/null) || return 1
    case "$executable" in "$SERVER"|"$SERVER (deleted)") ;; *) return 1 ;; esac
    # CLI migration/recovery processes use the same executable. Never signal them.
    {
        IFS= read -r -d '' first_arg || return 1
        if IFS= read -r -d '' second_arg; then return 1; fi
    } < "/proc/$candidate/cmdline" 2>/dev/null || return 1
}
instance_pids() {
    local proc candidate
    for proc in /proc/[0-9]*/exe; do
        candidate=${proc#/proc/}; candidate=${candidate%/exe}
        if service_pid "$candidate"; then printf '%s\n' "$candidate"; fi
    done
}
healthy() {
    [ -S "$SOCKET" ] && curl -fsS --max-time 2 --unix-socket "$SOCKET" http://localhost/health >/dev/null 2>&1
}
is_running() {
    [ -r "$PID_FILE" ] || return 1
    local candidate executable
    candidate=$(cat "$PID_FILE")
    service_pid "$candidate" || return 1
    executable=$(readlink "/proc/$candidate/exe" 2>/dev/null) || return 1
    [ "$executable" = "$SERVER" ] && healthy
}
stop_pid() {
    local candidate="$1" attempt
    service_pid "$candidate" || return 0
    kill -TERM "$candidate" 2>/dev/null || true
    for attempt in $(seq 1 10); do
        service_pid "$candidate" || return 0
        sleep 1
    done
    if service_pid "$candidate"; then kill -KILL "$candidate" 2>/dev/null || true; fi
    for attempt in $(seq 1 5); do
        service_pid "$candidate" || return 0
        sleep 1
    done
    ! service_pid "$candidate"
}
stop_instances() {
    local candidate
    for candidate in $(instance_pids); do stop_pid "$candidate" || return 1; done
    [ -z "$(instance_pids)" ]
}
control_lock() {
    mkdir -p "$TRIM_PKGVAR"
    exec 9>"$TRIM_PKGVAR/lifecycle.lock"
    flock -w 45 9 || { report '短剧启动失败：无法取得生命周期锁，可能仍有迁移或旧实例占用数据目录'; return 1; }
}
STARTED_PID=""
cleanup_failed_start() {
    local result=$?
    trap - EXIT INT TERM
    if [ "$result" -ne 0 ] && [ -n "$STARTED_PID" ]; then
        if ! stop_pid "$STARTED_PID"; then
            report "短剧进程 ${STARTED_PID} 未能退出，保留 PID 与日志供检查"
            exit "$result"
        fi
        wait "$STARTED_PID" 2>/dev/null || true
        if [ -r "$PID_FILE" ] && [ "$(cat "$PID_FILE")" = "$STARTED_PID" ]; then
            rm -f "$PID_FILE" "$SOCKET"
        fi
        report "短剧启动未就绪，已回收本次进程；详细原因见 ${LOG_FILE}"
    fi
    exit "$result"
}
case "${1:-}" in
start)
    command -v flock >/dev/null && command -v curl >/dev/null || { echo '启动需要 flock 和 curl' >&2; exit 1; }
    control_lock
    is_running && exit 0
    [ -x "$SERVER" ] && [ -f "${TRIM_APPDEST}/ui/index.html" ] || { report "短剧启动失败：应用文件不完整（${SERVER} 或 ui/index.html 缺失）"; exit 1; }
    SAVED_PORT=""
    if [ -f "$PORT_FILE" ]; then SAVED_PORT=$(cat -- "$PORT_FILE"); fi
    APP_PORT="${wizard_app_port:-${SAVED_PORT:-${wizard_port:-8688}}}"
    if [ "${wizard_upgrade_app_port+x}" = x ] || [ -n "${TRIM_OLD_APPVER:-}" ]; then
        # 升级留空时优先沿用已生效端口，再回落到旧安装配置。
        APP_PORT="${wizard_upgrade_app_port:-${SAVED_PORT:-$APP_PORT}}"
    fi
    if ! [[ "$APP_PORT" =~ ^[1-9][0-9]{3,4}$ ]] || ! ((APP_PORT >= 1024 && APP_PORT <= 65535)); then
        report '短剧启动失败：应用端口必须是 1024–65535 的整数'
        exit 1
    fi
    # Recover a healthy service whose pid file was lost without starting another.
    for candidate in $(instance_pids); do
        if [ "$(readlink "/proc/$candidate/exe" 2>/dev/null)" = "$SERVER" ] && healthy; then
            printf '%s\n' "$candidate" > "$PID_FILE"
            exit 0
        fi
    done
    stop_instances || { report '短剧启动失败：旧实例未能安全退出'; exit 1; }
    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 DRAMA_DEV=0 DRAMA_DATA_DIR="$DATA_DIR" DRAMA_FRONTEND_DIR="${TRIM_APPDEST}/ui"
    export FNNAS_GATEWAY_SOCKET="$SOCKET" FNNAS_GATEWAY_PREFIX=/app/leelaa-drama
    export DRAMA_FNOS_PORT="$APP_PORT" DRAMA_FNOS_TLS_DIR="${TRIM_PKGVAR}/tls"
    export FFMPEG_PATH="${TRIM_APPDEST}/bin/ffmpeg"
    unset DRAMA_MEDIA_ROOT
    export RUST_LOG=info
    trap cleanup_failed_start EXIT
    trap 'exit 1' INT TERM
    "$SERVER" 9>&- >> "$LOG_FILE" 2>&1 &
    STARTED_PID=$!
    printf '%s\n' "$STARTED_PID" > "$PID_FILE"
    for attempt in $(seq 1 "$START_TIMEOUT"); do
        # Fork/exec is asynchronous: a live child gets time to enter the binary.
        kill -0 "$STARTED_PID" 2>/dev/null || { report "短剧启动失败：服务进程已退出，请核对应用端口 ${APP_PORT}，详细日志见 ${LOG_FILE}"; exit 1; }
        if service_pid "$STARTED_PID" && healthy; then
            # 网关与直连监听就绪后才更新持久端口，失败时保留上次配置。
            if [ "$APP_PORT" != "$SAVED_PORT" ]; then
                PORT_TEMP=$(mktemp "${PORT_FILE}.XXXXXX")
                if ! printf '%s\n' "$APP_PORT" > "$PORT_TEMP" || ! mv -f -- "$PORT_TEMP" "$PORT_FILE"; then
                    rm -f -- "$PORT_TEMP"
                    report '短剧启动失败：无法保存应用端口'
                    exit 1
                fi
            fi
            trap - EXIT INT TERM
            exit 0
        fi
        sleep 1
    done
    report "短剧启动失败：${START_TIMEOUT} 秒内未通过 Unix socket 健康检查，详细日志见 ${LOG_FILE}"
    exit 1
    ;;
stop)
    control_lock
    stop_instances
    rm -f "$PID_FILE" "$SOCKET"
    ;;
status)
    if is_running; then exit 0; fi
    exit 3
    ;;
*) exit 1 ;;
esac
