#!/bin/sh

PACKAGE_NAME="${SYNOPKG_PKGNAME:-fn-knock-synology}"
PKGDEST="${SYNOPKG_PKGDEST:-/var/packages/${PACKAGE_NAME}/target}"
PKGVAR="${SYNOPKG_PKGVAR:-/var/packages/${PACKAGE_NAME}/var}"
PKGTMP="${SYNOPKG_PKGTMP:-/var/packages/${PACKAGE_NAME}/tmp}"
PKGHOME="${SYNOPKG_PKGHOME:-/var/packages/${PACKAGE_NAME}/home}"
PID_FILE="${PKGVAR}/fn-knock.pid"
LOG_FILE="${PKGVAR}/fn-knock.log"
ENTRYPOINT="${PKGDEST}/bin/fn-knock-entrypoint"
BACKEND_PORT="${BACKEND_PORT:-7998}"
READINESS_MARKER="${PKGVAR}/runtime.ready"
RUNTIME_PID_DIR="${PKGVAR}/runtime/pids"
GATEWAY_PID_FILE="${RUNTIME_PID_DIR}/gateway.pid"
MANAGEMENT_PID_FILE="${RUNTIME_PID_DIR}/management.pid"
START_TIMEOUT_SECONDS="${FN_KNOCK_START_TIMEOUT_SECONDS:-${FN_KNOCK_SYNOLOGY_START_TIMEOUT_SECONDS:-300}}"
STOP_TIMEOUT_SECONDS="${FN_KNOCK_STOP_TIMEOUT_SECONDS:-${FN_KNOCK_SYNOLOGY_STOP_TIMEOUT_SECONDS:-75}}"
FORCE_KILL_TIMEOUT_SECONDS="${FN_KNOCK_FORCE_KILL_TIMEOUT_SECONDS:-${FN_KNOCK_SYNOLOGY_FORCE_KILL_TIMEOUT_SECONDS:-10}}"
LAUNCH_TRANSITION_TIMEOUT_SECONDS="${FN_KNOCK_LAUNCH_TRANSITION_TIMEOUT_SECONDS:-5}"

is_positive_integer() {
    case "${1:-}" in
        ''|*[!0-9]*|0) return 1 ;;
        *) return 0 ;;
    esac
}

pid_exists() {
    [ -r "${PID_FILE}" ] || return 1
    PID="$(cat "${PID_FILE}" 2>/dev/null)"
    case "${PID}" in
        ''|*[!0-9]*) return 1 ;;
    esac
    kill -0 "${PID}" 2>/dev/null || return 1
    if [ -r "/proc/${PID}/stat" ]; then
        process_stat="$(cat "/proc/${PID}/stat" 2>/dev/null)" || return 1
        process_stat="${process_stat##*) }"
        set -- ${process_stat}
        [ "${1:-}" != "Z" ] || return 1
    fi
    return 0
}

pid_is_running() {
    pid_exists || return 1
    [ -r "/proc/${PID}/cmdline" ] || return 0
    tr '\000' ' ' < "/proc/${PID}/cmdline" | grep -q 'fn-knock-entrypoint'
}

pid_owns_isolated_group() {
    [ -n "${PID:-}" ] || return 1
    if [ -r "/proc/${PID}/stat" ]; then
        process_stat="$(cat "/proc/${PID}/stat" 2>/dev/null)" || return 1
        process_stat="${process_stat##*) }"
        set -- ${process_stat}
        [ "${3:-}" = "${PID}" ] && [ "${4:-}" = "${PID}" ]
        return
    fi
    process_group="$(ps -o pgid= -p "${PID}" 2>/dev/null | tr -d ' ')"
    [ "${process_group}" = "${PID}" ]
}

recorded_child_is_running() {
    child_pid_file="$1"
    child_command="$2"
    [ -r "${child_pid_file}" ] || return 1
    CHILD_PID="$(cat "${child_pid_file}" 2>/dev/null)"
    case "${CHILD_PID}" in
        ''|*[!0-9]*) return 1 ;;
    esac
    kill -0 "${CHILD_PID}" 2>/dev/null || return 1
    if [ -r "/proc/${CHILD_PID}/cmdline" ]; then
        tr '\000' ' ' < "/proc/${CHILD_PID}/cmdline" | grep -q "${child_command}"
    else
        ps -o command= -p "${CHILD_PID}" 2>/dev/null | grep -q "${child_command}"
    fi
}

recorded_children_are_running() {
    recorded_child_is_running "${MANAGEMENT_PID_FILE}" 'server-admin-rs' || \
        recorded_child_is_running "${GATEWAY_PID_FILE}" 'go-reauth-proxy'
}

signal_recorded_child() {
    signal="$1"
    child_pid_file="$2"
    child_command="$3"
    if recorded_child_is_running "${child_pid_file}" "${child_command}"; then
        kill "-${signal}" "${CHILD_PID}" 2>/dev/null || true
    fi
}

stop_recorded_child() {
    signal="$1"
    child_pid_file="$2"
    child_command="$3"
    timeout="$4"
    signal_recorded_child "${signal}" "${child_pid_file}" "${child_command}"
    elapsed=0
    while recorded_child_is_running "${child_pid_file}" "${child_command}" && \
        [ "${elapsed}" -lt "${timeout}" ]; do
        elapsed=$((elapsed + 1))
        sleep 1
    done
    ! recorded_child_is_running "${child_pid_file}" "${child_command}"
}

stop_recorded_children() {
    signal="$1"
    timeout="$2"
    stop_recorded_child "${signal}" "${GATEWAY_PID_FILE}" 'go-reauth-proxy' "${timeout}" || return 1
    stop_recorded_child "${signal}" "${MANAGEMENT_PID_FILE}" 'server-admin-rs' "${timeout}"
}

remove_runtime_pid_files() {
    rm -f "${PID_FILE}" "${MANAGEMENT_PID_FILE}" "${GATEWAY_PID_FILE}" "${READINESS_MARKER}"
}

signal_service() {
    signal="$1"
    pid_is_running || return 0
    if pid_owns_isolated_group; then
        # dash and BusyBox sh reject `kill ... -- -PGID`; the negative operand is portable.
        kill "-${signal}" "-${PID}" 2>/dev/null || kill "-${signal}" "${PID}" 2>/dev/null || true
    else
        kill "-${signal}" "${PID}" 2>/dev/null || true
    fi
}

signal_supervisor() {
    signal="$1"
    pid_is_running || return 0
    kill "-${signal}" "${PID}" 2>/dev/null || true
}

wait_for_service_exit() {
    timeout="$1"
    elapsed=0
    while { pid_is_running || recorded_children_are_running; } && [ "${elapsed}" -lt "${timeout}" ]; do
        elapsed=$((elapsed + 1))
        sleep 1
    done
    ! pid_is_running && ! recorded_children_are_running
}

write_runtime_ports() {
    umask 022
    {
        printf 'ADMIN_TARGET_HOST=127.0.0.1\n'
        printf 'ADMIN_TARGET_PORT=%s\n' "${BACKEND_PORT}"
        printf 'BACKEND_PORT=%s\n' "${BACKEND_PORT}"
        printf 'AUTH_PORT=%s\n' "${AUTH_PORT:-7997}"
        printf 'GO_BACKEND_PORT=%s\n' "${GO_BACKEND_PORT:-7996}"
        printf 'GO_REPROXY_PORT=%s\n' "${GO_REPROXY_PORT:-7999}"
    } > "${PKGVAR}/runtime-ports.env"
    chmod 644 "${PKGVAR}/runtime-ports.env"
}

launch_service() {
    SESSION_LAUNCHER="$(command -v setsid 2>/dev/null || true)"

    umask 077
    if [ -n "${SESSION_LAUNCHER}" ]; then
        PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/syno/bin" \
        HOME="${PKGHOME}" \
        TMPDIR="${PKGTMP}" \
        FN_KNOCK_APP_HOME="${PKGDEST}" \
        FN_KNOCK_DATA_DIR="${PKGVAR}" \
        FN_KNOCK_GATEWAY_CONFIG_DIR="${PKGVAR}/gateway" \
        FN_KNOCK_SUPERVISOR_PID_FILE="${PID_FILE}" \
        FN_KNOCK_START_TIMEOUT_SECONDS="${START_TIMEOUT_SECONDS}" \
        FN_KNOCK_SYNOLOGY_START_TIMEOUT_SECONDS="${START_TIMEOUT_SECONDS}" \
        BACKEND_PORT="${BACKEND_PORT}" \
        AUTH_PORT="${AUTH_PORT:-7997}" \
        GO_BACKEND_PORT="${GO_BACKEND_PORT:-7996}" \
        GO_REPROXY_PORT="${GO_REPROXY_PORT:-7999}" \
        nohup "${SESSION_LAUNCHER}" "${ENTRYPOINT}" >> "${LOG_FILE}" 2>&1 &
    else
        PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/syno/bin" \
        HOME="${PKGHOME}" \
        TMPDIR="${PKGTMP}" \
        FN_KNOCK_APP_HOME="${PKGDEST}" \
        FN_KNOCK_DATA_DIR="${PKGVAR}" \
        FN_KNOCK_GATEWAY_CONFIG_DIR="${PKGVAR}/gateway" \
        FN_KNOCK_SUPERVISOR_PID_FILE="${PID_FILE}" \
        FN_KNOCK_START_TIMEOUT_SECONDS="${START_TIMEOUT_SECONDS}" \
        FN_KNOCK_SYNOLOGY_START_TIMEOUT_SECONDS="${START_TIMEOUT_SECONDS}" \
        BACKEND_PORT="${BACKEND_PORT}" \
        AUTH_PORT="${AUTH_PORT:-7997}" \
        GO_BACKEND_PORT="${GO_BACKEND_PORT:-7996}" \
        GO_REPROXY_PORT="${GO_REPROXY_PORT:-7999}" \
        nohup "${ENTRYPOINT}" >> "${LOG_FILE}" 2>&1 &
    fi
    # Keep the transient launcher PID in memory only. Writing it to PID_FILE
    # can race with fn-knock-entrypoint registering its actual supervisor PID.
    LAUNCHER_PID=$!
}

stop_service() {
    if ! pid_is_running && ! recorded_children_are_running; then
        remove_runtime_pid_files
        return 0
    fi

    if pid_is_running; then
        # Let the supervisor drain the public gateway before it stops the
        # authentication backend. Signalling the process group here would
        # terminate both children at once and recreate the broken-upstream gap.
        signal_supervisor TERM
    else
        stop_recorded_children TERM "${STOP_TIMEOUT_SECONDS}" || true
    fi
    if ! wait_for_service_exit "${STOP_TIMEOUT_SECONDS}"; then
        signal_service KILL
        stop_recorded_children KILL "${FORCE_KILL_TIMEOUT_SECONDS}" || true
        wait_for_service_exit "${FORCE_KILL_TIMEOUT_SECONDS}" || {
            printf 'fn-knock process group did not stop; PID %s is still running\n' "${PID}" \
                > "${SYNOPKG_TEMP_LOGFILE:-/dev/null}"
            return 1
        }
    fi
    remove_runtime_pid_files
}

start_service() {
    service_already_running=0
    if pid_is_running; then
        service_already_running=1
    else
        if recorded_children_are_running; then
            stop_service || return 1
        else
            remove_runtime_pid_files
        fi
    fi
    if [ "${service_already_running}" -eq 0 ]; then
        mkdir -p "${PKGVAR}" "${PKGTMP}" "${PKGHOME}"
        write_runtime_ports
        launch_service
    fi

    started_at="$(date '+%s')"
    deadline=$((started_at + START_TIMEOUT_SECONDS))
    launch_transition_deadline=$((started_at + LAUNCH_TRANSITION_TIMEOUT_SECONDS))
    while [ "$(date '+%s')" -lt "${deadline}" ]; do
        # A forking setsid launcher may exit just before fn-knock-entrypoint
        # atomically registers the long-lived supervisor PID. Allow only this
        # short handoff window, then require the self-registered process.
        if ! pid_exists && [ "$(date '+%s')" -ge "${launch_transition_deadline}" ]; then
            if [ -n "${LAUNCHER_PID:-}" ] && kill -0 "${LAUNCHER_PID}" 2>/dev/null; then
                kill -TERM "${LAUNCHER_PID}" 2>/dev/null || true
            fi
            rm -f "${PID_FILE}"
            printf 'fn-knock exited during startup; see %s\n' "${LOG_FILE}" \
                > "${SYNOPKG_TEMP_LOGFILE:-/dev/null}"
            return 1
        fi
        if [ -f "${READINESS_MARKER}" ]; then
            readiness_failure=""
            if ! pid_is_running; then
                readiness_failure="supervisor PID does not identify fn-knock-entrypoint"
            elif ! recorded_child_is_running "${MANAGEMENT_PID_FILE}" 'server-admin-rs'; then
                readiness_failure="management PID does not identify server-admin-rs"
            elif ! recorded_child_is_running "${GATEWAY_PID_FILE}" 'go-reauth-proxy'; then
                readiness_failure="gateway PID does not identify go-reauth-proxy"
            fi
            if [ -z "${readiness_failure}" ]; then
                return 0
            fi
            printf '[fn-knock] readiness rejected: %s\n' "${readiness_failure}" >> "${LOG_FILE}"
            stop_service || true
            printf 'fn-knock readiness responded but process validation failed: %s; see %s\n' \
                "${readiness_failure}" "${LOG_FILE}" > "${SYNOPKG_TEMP_LOGFILE:-/dev/null}"
            return 1
        fi
        sleep 1
    done

    if ! pid_exists && [ -n "${LAUNCHER_PID:-}" ] && kill -0 "${LAUNCHER_PID}" 2>/dev/null; then
        kill -TERM "${LAUNCHER_PID}" 2>/dev/null || true
    fi
    stop_service || true
    printf 'fn-knock readiness timed out after %s seconds; see %s\n' \
        "${START_TIMEOUT_SECONDS}" "${LOG_FILE}" > "${SYNOPKG_TEMP_LOGFILE:-/dev/null}"
    return 1
}

validate_configuration() {
    is_positive_integer "${START_TIMEOUT_SECONDS}" || return 1
    is_positive_integer "${STOP_TIMEOUT_SECONDS}" || return 1
    is_positive_integer "${FORCE_KILL_TIMEOUT_SECONDS}" || return 1
    is_positive_integer "${LAUNCH_TRANSITION_TIMEOUT_SECONDS}" || return 1
    return 0
}

case "${1:-}" in
    start)
        validate_configuration || exit 1
        start_service
        ;;
    stop)
        validate_configuration || exit 1
        stop_service
        ;;
    status)
        if pid_is_running && [ -f "${READINESS_MARKER}" ] && \
            recorded_child_is_running "${MANAGEMENT_PID_FILE}" 'server-admin-rs' && \
            recorded_child_is_running "${GATEWAY_PID_FILE}" 'go-reauth-proxy'; then
            exit 0
        fi
        { [ -e "${PID_FILE}" ] || [ -e "${MANAGEMENT_PID_FILE}" ] || \
            [ -e "${GATEWAY_PID_FILE}" ] || [ -e "${READINESS_MARKER}" ]; } && exit 1
        exit 3
        ;;
    prestart)
        [ -x "${ENTRYPOINT}" ] || {
            printf 'Missing executable: %s\n' "${ENTRYPOINT}" > "${SYNOPKG_TEMP_LOGFILE:-/dev/null}"
            exit 1
        }
        validate_configuration || {
            printf 'Invalid fn-knock lifecycle timeout configuration\n' > "${SYNOPKG_TEMP_LOGFILE:-/dev/null}"
            exit 1
        }
        ;;
    prestop) ;;
    *) exit 1 ;;
esac

exit $?
