#!/bin/bash

PKG="Fail2BanCommunity"
PKG_DIR="/var/packages/${PKG}"
ALIVE_FILE="${PKG_DIR}/var/fail2ban-data/.alive"
LOG_DIR="${PKG_DIR}/var/log"
LOG_FILE="${LOG_DIR}/pkg-debug.log"
MAX_AGE=120
# Container image build / first start after upgrade can exceed 90s; DSM maps "running" to recent .alive.
WAIT_SECS=240

timestamp() {
    date '+%Y-%m-%d %H:%M:%S %z'
}

write_log() {
    local msg="$*"
    mkdir -p "$LOG_DIR" 2>/dev/null || true
    printf '%s [%s] pid=%s %s\n' "$(timestamp)" "$PKG" "$$" "$msg" >>"$LOG_FILE" 2>/dev/null || true
    if command -v logger >/dev/null 2>&1; then
        logger -t "${PKG}[start-stop-status]" -- "$msg" 2>/dev/null || true
    fi
}

alive_state_summary() {
    local now last age exists size

    now="$(date +%s)"

    if [ -e "$ALIVE_FILE" ]; then
        exists=1
        size="$(wc -c <"$ALIVE_FILE" 2>/dev/null || echo "unknown")"
    else
        exists=0
        size="missing"
    fi

    last="$(cat "$ALIVE_FILE" 2>/dev/null || true)"

    case "$last" in
        ''|*[!0-9]*)
            age="invalid"
            ;;
        *)
            age=$((now - last))
            ;;
    esac

    printf 'alive_exists=%s alive_size=%s alive_value=%s now=%s alive_age=%s' \
        "$exists" \
        "$size" \
        "${last:-<empty>}" \
        "$now" \
        "$age"
}

alive_recent() {
    local now last

    [ -f "$ALIVE_FILE" ] || return 1

    now="$(date +%s)"
    last="$(cat "$ALIVE_FILE" 2>/dev/null || echo 0)"

    case "$last" in
        ''|*[!0-9]*)
            return 1
            ;;
    esac

    [ $((now - last)) -le "$MAX_AGE" ]
}

wait_until_running() {
    local end
    end=$(( $(date +%s) + WAIT_SECS ))

    write_log "action=start phase=wait_begin $(alive_state_summary)"

    while [ "$(date +%s)" -le "$end" ]; do
        if alive_recent; then
            write_log "action=start phase=wait_success $(alive_state_summary)"
            return 0
        fi
        sleep 2
    done

    write_log "action=start phase=wait_timeout $(alive_state_summary)"
    return 1
}

case "$1" in
    start)
        write_log "action=start phase=entry $(alive_state_summary)"
        wait_until_running
        rc=$?
        write_log "action=start phase=exit rc=$rc $(alive_state_summary)"
        exit $rc
        ;;
    stop)
        write_log "action=stop phase=entry $(alive_state_summary)"
        rm -f "$ALIVE_FILE" 2>/dev/null || true
        write_log "action=stop phase=exit rc=0 $(alive_state_summary)"
        exit 0
        ;;
    status)
        write_log "action=status phase=entry $(alive_state_summary)"
        alive_recent
        rc=$?
        write_log "action=status phase=exit rc=$rc $(alive_state_summary)"
        exit $rc
        ;;
    log)
        mkdir -p "$LOG_DIR" 2>/dev/null || true
        touch "$LOG_FILE" 2>/dev/null || true
        write_log "action=log phase=exit rc=0 $(alive_state_summary)"
        exit 0
        ;;
    *)
        write_log "action=invalid arg=${1:-<empty>} $(alive_state_summary)"
        echo "Usage: $0 {start|stop|status}" >&2
        exit 1
        ;;
esac
