#!/usr/bin/env bash
# infra/bin/fly-runtime — which runtime the live fly runs: the legacy loop (`flysim`) or the
# session runtime (`flysim-session`, SERVE-01).
#
# Usage (INSIDE the container, as root):
#   fly-runtime status              print `legacy` or `session`, and what flysim.service runs
#   fly-runtime session [--no-restart] [--no-fallback]
#   fly-runtime legacy  [--no-restart]
#   fly-runtime fallback [reason]   (run by fly-runtime-fallback.service, see below; idempotent)
#
# CUT-01 calls `fly-runtime session` after its zero-divergence shadow; `fly-runtime legacy` is
# the one-command rollback (port decisions, 2026-09-23). Neither migrates any data: both
# binaries read and write the same FLYSIM01 stores, event log, sugar journal and chat sidecar.
#
# How the switch works. flysim.service stays the fly's one unit name, and the runtime it runs
# is chosen by one drop-in, ${DROPIN}:
#
#   [Service]
#   ExecStart=
#   ExecStart=/opt/fly/current/flysim-session
#   Environment=FLY_SESSION_DIR=/run/fly/session
#
# i.e. flysim-session.service's ExecStart and its one extra variable (the standalone unit and
# this drop-in are kept identical by infra/tests/lint.sh). Everything else that names
# flysim.service -- fly.target, flyedge.service's Requires=, fly-watchdog's checks and escalation,
# fly-loop-recover's `sudo systemctl restart flysim.service` and its sudoers line,
# fly-loop-reset, fly-reset-to-milestone, the unstick rule, `journalctl -u flysim`, the cpuset
# drop-in -- therefore keeps working unchanged, a reboot keeps the choice, and 05-deploy.sh (which
# converges unit files but never removes a drop-in) keeps it across deploys. 05-deploy.sh refuses
# a release without flysim-session while the drop-in is present.
#
# `session` refuses unless the release has flysim-session and its --print-compatibility equals
# flysim's (the store is shared, so the two must restore each other's checkpoints). After the
# restart it waits for /healthz (FLY_RUNTIME_HEALTH_TIMEOUT, default 300 s: the connectome load and
# the restore) and a snapshot that has advanced; if the session runtime does not come up healthy
# it switches back to legacy by itself and exits 1 (--no-fallback leaves it to the operator).
#
# The fallback survives the invocation (C1 of the SERVE-01 review). The drop-in also carries
#
#   [Unit]
#   OnFailure=fly-runtime-fallback.service
#   StartLimitIntervalSec=600
#   StartLimitBurst=3
#   [Service]
#   RestartMode=direct
#
# RestartMode=direct is essential (systemd >= 254; verified on 257): with the default
# RestartMode=normal the unit passes through `failed` before every Restart=always restart and
# OnFailure= fires on the FIRST crash, watchdog kill or start timeout. With `direct` the unit
# goes from one start straight to the next and only the start limit puts it in `failed`. So while the session runtime is selected, three starts of flysim.service inside ten minutes
# (crashes, watchdog kills, a start that never becomes ready, the restarts fly-watchdog and
# fly-loop-recover make for a stream that does not come up) end in the failed state, and systemd
# runs fly-runtime-fallback.service, i.e. `fly-runtime fallback`: write ${FELLBACK_FILE}, remove
# the drop-in, daemon-reload, restart flysim.service (now the legacy binary) and log a line. That
# holds across reboots, watchdog and loop-recover restarts and deploys, none of which go through
# `fly-runtime session`. It is idempotent (a lock, and a no-op once the drop-in is gone) and it
# keeps the drop-in when there is no executable legacy binary, so it never swaps one runtime that
# cannot start for another. `fly-runtime session` deletes the reason file; `status` shows it.
#
# During a switch fly-runtime traps INT, TERM and HUP (and any failure): an interrupted `session`
# puts the previous state back (drop-in removed, or the earlier one restored) and restarts
# flysim.service on it, so a dropped ssh never leaves a drop-in that was not health-checked.
#
# Every switch is logged to the journal (tag fly-runtime) and appended to ${RUNTIME_LOG}.
set -euo pipefail

: "${FLY_RELEASE_DIR:=/opt/fly/current}"
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
: "${FLY_SERVICE:=flysim.service}"
: "${FLY_RUNTIME_HEALTH_TIMEOUT:=300}"
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
: "${FLY_SYSTEMD_DIR:=/etc/systemd/system}"
: "${FLY_RUNTIME_LOG:=/var/lib/fly/runtime.log}"
: "${FLY_RUNTIME_FELLBACK:=/run/fly/runtime-fellback.json}"
: "${FLY_RUNTIME_LOCK:=/run/fly/runtime.lock}"
: "${FLY_RUNTIME_LOCK_WAIT:=150}"
DROPIN_DIR="${FLY_SYSTEMD_DIR}/${FLY_SERVICE}.d"
DROPIN="${DROPIN_DIR}/10-runtime.conf"
RUNTIME_LOG="$FLY_RUNTIME_LOG"
FELLBACK_FILE="$FLY_RUNTIME_FELLBACK"
FALLBACK_UNIT=fly-runtime-fallback.service
SESSION_BIN="${FLY_RELEASE_DIR}/flysim-session"
LEGACY_BIN="${FLY_RELEASE_DIR}/flysim"
SESSION_DIR=/run/fly/session

log() { echo "fly-runtime: $*" >&2; }
die() { log "$*"; exit 1; }

usage() {
    echo "usage: fly-runtime status | session [--no-restart] [--no-fallback] | legacy [--no-restart] | fallback [reason]" >&2
    exit 2
}

current() {
    if [ -f "$DROPIN" ]; then echo session; else echo legacy; fi
}

record() {
    local line
    line="$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*"
    if command -v logger >/dev/null 2>&1; then
        logger -t fly-runtime -- "$*" || true
    fi
    mkdir -p "$(dirname "$RUNTIME_LOG")" 2>/dev/null || true
    echo "$line" >>"$RUNTIME_LOG" 2>/dev/null || log "could not append to $RUNTIME_LOG"
}

# The compatibility string a binary would write, with the service's own environment: fly.env is
# systemd's EnvironmentFile syntax, read as KEY=VALUE lines rather than sourced as shell.
compat_of() {
    local -a vars=()
    local line key value
    if [ -f "$FLY_ENV_FILE" ]; then
        while IFS= read -r line || [ -n "$line" ]; do
            [[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || continue
            key="${line%%=*}"
            value="${line#*=}"
            value="${value%\"}"
            value="${value#\"}"
            vars+=("${key}=${value}")
        done <"$FLY_ENV_FILE"
    fi
    env "${vars[@]}" "$1" --print-compatibility 2>/dev/null | tr -d '\r'
}

write_dropin() {
    mkdir -p "$DROPIN_DIR"
    local tmp="${DROPIN}.tmp.$$"
    cat >"$tmp" <<EOF
# Written by fly-runtime session (SERVE-01): flysim.service runs the session runtime.
# \`fly-runtime legacy\` removes this file, and so does fly-runtime-fallback.service (OnFailure=,
# after three starts in ten minutes). RestartMode=direct is what makes OnFailure= wait for the start
# limit: systemd >= 254 otherwise passes through the failed state (and OnFailure=) before EVERY auto-restart.
# Keep [Service] in step with units/flysim-session.service.
[Unit]
OnFailure=${FALLBACK_UNIT}
StartLimitIntervalSec=600
StartLimitBurst=3
[Service]
RestartMode=direct
ExecStart=
ExecStart=${SESSION_BIN}
Environment=FLY_SESSION_DIR=${SESSION_DIR}
Environment=MALLOC_ARENA_MAX=2
EOF
    chmod 0644 "$tmp"
    mv -f "$tmp" "$DROPIN"
}

# /healthz 200, then a snapshot whose frame moved: the loop is running, not just listening.
healthy() {
    local deadline=$(( $(date +%s) + FLY_RUNTIME_HEALTH_TIMEOUT ))
    local first=""
    while [ "$(date +%s)" -lt "$deadline" ]; do
        if [ -n "$old_invocation" ] \
            && [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then
            sleep 1
            continue
        fi
        if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
            local frame
            frame="$(curl -fsS "${FLY_CONTROL_URL}/status" 2>/dev/null \
                | sed -n 's/.*"frame":\([0-9][0-9]*\).*/\1/p' | head -n1)"
            if [ -n "$frame" ]; then
                if [ -z "$first" ]; then
                    first="$frame"
                elif [ "$frame" -gt "$first" ]; then
                    log "healthy: frame ${first} -> ${frame}"
                    return 0
                fi
            fi
        fi
        sleep 1
    done
    return 1
}

# One lock (${FLY_RUNTIME_LOCK}) serialises every change of the drop-in: `fallback`, `session`,
# `legacy` and the rollback in on_exit. A switch holds it from before it reads the current state
# until its restart has been queued (`restart --no-block`), and lets go before the health wait, so
# an OnFailure= fallback is never held up by a start that does not become ready. Re-entrant per
# process. Waits FLY_RUNTIME_LOCK_WAIT (150 s).
locked=0
take_lock() {
    if [ "$locked" -eq 1 ]; then return 0; fi
    mkdir -p "$(dirname "$FLY_RUNTIME_LOCK")" 2>/dev/null || true
    exec 9>>"$FLY_RUNTIME_LOCK"
    if flock -w "$FLY_RUNTIME_LOCK_WAIT" 9; then locked=1; return 0; fi
    log "could not take ${FLY_RUNTIME_LOCK} within ${FLY_RUNTIME_LOCK_WAIT} s"
    return 1
}
drop_lock() {
    exec 9>&-
    locked=0
}

restarted=0
old_invocation=""
restart_and_check() {
    systemctl daemon-reload
    systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
    log "restarting ${FLY_SERVICE} on the $(current) runtime"
    restarted=1
    # --no-block: a blocking restart of a unit that never becomes READY holds this process (and
    # the lock) for minutes, starving the OnFailure= fallback. `healthy` therefore has to prove
    # that it is talking to the NEW invocation, not the old process that is still shutting down.
    old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
    systemctl restart --no-block "$FLY_SERVICE" || { drop_lock; return 1; }
    drop_lock
    healthy
}

# The fallback to legacy, shared by `fly-runtime session` (its own health check) and by
# fly-runtime-fallback.service (OnFailure= in the drop-in). Idempotent and serialised: whoever
# gets the lock second finds the drop-in gone and does nothing. It never removes the drop-in
# unless legacy can start, and it puts the drop-in back if flysim.service cannot be restarted,
# so at least one runtime is always startable. Restarts with --no-block: the caller (or the
# watchdog) judges health, and a oneshot unit must not sit in a 90 s notify start.
do_fallback() {
    local reason="$1" result nrestarts saved
    take_lock || log "continuing without the lock"
    if [ ! -f "$DROPIN" ]; then
        log "fallback: the legacy runtime is already selected; nothing to do"
        return 0
    fi
    if [ ! -x "$LEGACY_BIN" ]; then
        record "fallback REFUSED (${reason}): no executable ${LEGACY_BIN}; the session drop-in stays"
        return 1
    fi
    result="$(systemctl show -p Result --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
    nrestarts="$(systemctl show -p NRestarts --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
    reason="${reason//[\"\\]/}"
    reason="${reason//$'\n'/ }"
    mkdir -p "$(dirname "$FELLBACK_FILE")" 2>/dev/null || true
    printf '{"at":"%s","from":"session","to":"legacy","reason":"%s","unitResult":"%s","nRestarts":"%s"}\n' \
        "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$reason" "${result:-unknown}" "${nrestarts:-}" \
        >"${FELLBACK_FILE}.tmp.$$" 2>/dev/null || true
    mv -f "${FELLBACK_FILE}.tmp.$$" "$FELLBACK_FILE" 2>/dev/null || log "could not write ${FELLBACK_FILE}"
    saved="$(mktemp "${DROPIN}.saved.XXXXXX")"
    cp -f "$DROPIN" "$saved"
    rm -f "$DROPIN"
    rmdir "$DROPIN_DIR" 2>/dev/null || true
    record "legacy (automatic fallback: ${reason}; was session)"
    systemctl daemon-reload || true
    systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
    restarted=1
    if systemctl restart --no-block "$FLY_SERVICE"; then
        rm -f "$saved"
        return 0
    fi
    # Could not even queue the restart: keep what was running, and say so.
    mkdir -p "$DROPIN_DIR" && mv -f "$saved" "$DROPIN"
    systemctl daemon-reload || true
    rm -f "$FELLBACK_FILE"
    record "fallback FAILED (${reason}): could not restart ${FLY_SERVICE}; the session drop-in is back"
    return 1
}

# An interrupted or failed switch puts the previous state back. `switching` is 1 from just
# before the drop-in is touched until the switch has finished; `prev_dropin` is a copy of the
# drop-in that was there before (empty: none, i.e. legacy). The rollback runs under the lock and
# does nothing when a fallback has completed since the switch began (FELLBACK_FILE exists: the
# switch deleted it under the lock, only a finished fallback writes it): restoring the older
# drop-in then would strand the stream on the session runtime after it was taken off.
switching=0
switch_target=""
prev_dropin=""
# shellcheck disable=SC2317  # runs from the EXIT trap
on_exit() {
    local rc=$?
    trap - EXIT INT TERM HUP
    if [ "$switching" -eq 1 ]; then
        switching=0
        take_lock || true
        if [ "$switch_target" = session ] && [ -f "$FELLBACK_FILE" ]; then
            record "legacy (switch to session interrupted or failed (exit ${rc}); a fallback completed meanwhile, not restoring the older drop-in)"
            restarted=0
        elif [ "$switch_target" = session ]; then
            if [ -n "$prev_dropin" ] && [ -f "$prev_dropin" ]; then
                mkdir -p "$DROPIN_DIR" && cp -f "$prev_dropin" "$DROPIN"
            else
                rm -f "$DROPIN"
                rmdir "$DROPIN_DIR" 2>/dev/null || true
            fi
            record "$(current) (switch to session interrupted or failed (exit ${rc}); rolled back)"
        else
            record "$(current) (switch to legacy interrupted (exit ${rc}))"
        fi
        systemctl daemon-reload || true
        if [ "$restarted" -eq 1 ]; then
            systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
            systemctl restart --no-block "$FLY_SERVICE" || true
        fi
    fi
    [ -z "$prev_dropin" ] || rm -f "$prev_dropin"
    exit "$rc"
}
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP

[ $# -ge 1 ] || usage
command="$1"; shift
restart=1
fallback=1
fallback_reason=""
if [ "$command" = fallback ]; then fallback_reason="$*"; set --; fi
for arg in "$@"; do
    case "$arg" in
        --no-restart) restart=0 ;;
        --no-fallback) fallback=0 ;;
        *) usage ;;
    esac
done

case "$command" in
    status)
        current
        if [ -f "$FELLBACK_FILE" ]; then echo "  fell back to legacy: $(cat "$FELLBACK_FILE")"; fi
        systemctl show -p ExecStart --value "$FLY_SERVICE" 2>/dev/null | sed -n 's/.*path=\([^ ;]*\).*/  flysim.service runs \1/p' || true
        exit 0
        ;;
    session|legacy) ;;
    fallback)
        [ "$(id -u)" -eq 0 ] || die "run as root"
        do_fallback "${fallback_reason:-flysim.service failed on the session runtime (OnFailure=)}"
        exit $?
        ;;
    *) usage ;;
esac

[ "$(id -u)" -eq 0 ] || die "run as root (it writes ${DROPIN} and restarts ${FLY_SERVICE})"

if [ "$command" = session ]; then
    [ -x "$SESSION_BIN" ] || die "this release has no ${SESSION_BIN}; the session runtime ships from SERVE-01 on"
    [ -x "$LEGACY_BIN" ] || die "no ${LEGACY_BIN}"
    legacy_compat="$(compat_of "$LEGACY_BIN")"
    session_compat="$(compat_of "$SESSION_BIN")"
    [ -n "$session_compat" ] || die "${SESSION_BIN} --print-compatibility printed nothing (see its stderr); not switching"
    if [ "$legacy_compat" != "$session_compat" ]; then
        die "the two runtimes would write different checkpoints; not switching.
  flysim:         ${legacy_compat}
  flysim-session: ${session_compat}"
    fi
    take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
    before="$(current)"
    if [ -f "$DROPIN" ]; then
        prev_dropin="$(mktemp "${DROPIN}.prev.XXXXXX")"
        cp -f "$DROPIN" "$prev_dropin"
    fi
    switch_target=session
    switching=1
    rm -f "$FELLBACK_FILE"
    write_dropin
    record "session (was ${before}); compatibility ${session_compat}"
    if [ "$restart" -ne 1 ]; then
        systemctl daemon-reload
        switching=0
        log "drop-in written; restart ${FLY_SERVICE} to apply"
        exit 0
    fi
    if restart_and_check; then
        # OnFailure= may have fallen back while we waited (a healthy legacy would pass the
        # check above too): only report success if the session drop-in is still what runs.
        if [ -f "$DROPIN" ] && [ ! -f "$FELLBACK_FILE" ]; then
            switching=0
            log "flysim.service runs the session runtime"
            exit 0
        fi
        switching=0
        log "the session runtime failed and ${FALLBACK_UNIT} fell back to legacy: $(cat "$FELLBACK_FILE" 2>/dev/null)"
        exit 1
    fi
    log "the session runtime did not come up healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s"
    if [ "$fallback" -eq 1 ]; then
        do_fallback "the session runtime was not healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s of the switch" || true
        switching=0
        if healthy; then
            log "fell back to the legacy runtime; it is healthy"
        else
            log "fell back to the legacy runtime, and it is NOT healthy either: check journalctl -u ${FLY_SERVICE}"
        fi
    else
        switching=0
    fi
    exit 1
fi

# legacy
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
before="$(current)"
switch_target=legacy
switching=1
rm -f "$DROPIN"
rmdir "$DROPIN_DIR" 2>/dev/null || true
record "legacy (was ${before})"
[ "$restart" -eq 1 ] || { systemctl daemon-reload; switching=0; log "drop-in removed; restart ${FLY_SERVICE} to apply"; exit 0; }
if restart_and_check; then
    switching=0
    log "flysim.service runs the legacy runtime"
    exit 0
fi
switching=0
die "the legacy runtime did not come up healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s: check journalctl -u ${FLY_SERVICE}"
