#!/bin/sh
# Local operator entry point. Transport is SSH; supervision is entirely remote systemd.
set -eu
umask 077
HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
ROOT=$(CDPATH='' cd -- "$HERE/../.." && pwd)
# shellcheck source=tools/remote/pins.sh
. "$HERE/pins.sh"
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
valid_nonce() {
    case "$1" in *[!0-9a-f]*|'') return 1 ;; esac
    [ "${#1}" -eq 16 ]
}
set_names() {
    valid_nonce "$nonce" || fail 'nonce must be 16 lowercase hex characters'
    case "$mode" in noop|disconnect|timeout|filc|pic) ;; *) fail 'invalid mode' ;; esac
    prefix="pi-c-s0-$nonce"
    owner="$prefix-owner.service"
    worker="$prefix-worker.service"
    cleanup="$prefix-cleanup.service"
    timer="$prefix-cleanup.timer"
    worker_seconds=300
    [ "$mode" != timeout ] || worker_seconds=3
    # pic mode compiles SQLite, libfossil and BearSSL under Fil-C and runs the
    # whole pic suite: a longer lease and more memory, still fully guarded.
    lease_seconds=600
    limits='TasksMax:64 MemoryMax:1G CPUQuota:100% LimitFSIZE:134217728'
    source_max=262144
    if [ "$mode" = pic ]; then
        # The suite under Fil-C passed 50 minutes once the TUI rounds landed.
        worker_seconds=6600
        lease_seconds=7200
        limits='TasksMax:128 MemoryMax:2G CPUQuota:200% LimitFSIZE:134217728'
        source_max=16777216
    fi
}
# The files a mode uploads. pic mode's list is fixed at prepare time by the
# snapshot index, so later repository edits cannot change a run.
source_list() {
    if [ "$mode" = pic ]; then
        sed 's/^[0-9a-f]*  //' "$run/snapshot/sources.sha256"
    else
        repo_sources
    fi
}
repo_sources() {
    if [ "$mode" = pic ]; then
        (cd "$ROOT" && find src vendor/zlib vendor/bearssl/inc vendor/bearssl/src test/pic test/tui -type f \
            \( -name '*.c' -o -name '*.h' -o -name '*.inc' -o -name '*.sh' -o -name '*.sse' -o -name '*.want' -o -name '*.sql' \) | LC_ALL=C sort)
        printf '%s\n' vendor/libfossil/sqlite3.c vendor/libfossil/sqlite3.h vendor/libfossil/shell.c vendor/libfossil/libfossil.c \
            vendor/libfossil/libfossil.h vendor/libfossil/libfossil-config.h tools/remote/payload.sh
        return
    fi
    printf '%s\n' test/qualification/qual.h test/qualification/fixture.c \
        test/qualification/oracle.c test/qualification/test_qualification.c \
        test/qualification/test_oracle_mutant.c test/qualification/replay.c \
        test/fuzz/corpus/empty.bin test/fuzz/corpus/dedup.bin \
        test/fuzz/corpus/admit_commit.bin test/fuzz/corpus/effect_before_receipt.bin \
        test/fuzz/corpus/truncated.bin test/fuzz/corpus/unsafe_interrupt.bin \
        test/fuzz/corpus/retry-after-uncommitted-crash.bin tools/remote/payload.sh
}
manifest() {
    printf '%s\n' 'version=1' 'host=hetzner-hel' "nonce=$nonce" "mode=$mode" \
        "owner=$owner" "worker=$worker" "cleanup=$cleanup" "timer=$timer" \
        "worker_seconds=$worker_seconds" "lease_seconds=$lease_seconds" "cleanup_seconds=$lease_seconds" \
        'stop_seconds=5' 'uid=1000' 'gid=1000' \
        "limits=$limits" \
        'scope=trusted qualification fixtures; no aggregate disk quota or security sandbox' \
        'teardown=collect then teardown then reconcile; guard stays armed until absence verified' \
        "workspace=$REMOTE_HOME/.pi-c-s0-$nonce" "toolchain=$TOOLCHAIN" \
        "compiler=$COMPILER" "archive=$ARCHIVE" "archive_sha256=$ARCHIVE_SHA" \
        "compiler_sha256=$COMPILER_SHA" "runtime_libraries=${RUNTIME_LIBRARIES:-}" \
        "sources_index_sha256=$(shasum -a 256 "$run/snapshot/sources.sha256" | cut -d' ' -f1)" \
        "control_index_sha256=$(shasum -a 256 "$run/control/controls.sha256" | cut -d' ' -f1)"
    cat "$run/snapshot/sources.sha256" "$run/control/controls.sha256"
}
prepare() {
    [ ! -e "$run" ] && [ ! -L "$run" ] || fail 'local run path already exists'
    mkdir -m 700 "$run"
    mkdir "$run/snapshot" "$run/control"
    # Generated sources are not committed; build them so the snapshot has them.
    if [ "$mode" = pic ]; then
        make -s -C "$ROOT" src/changelog.inc >&2 || fail 'cannot generate src/changelog.inc'
    fi
    repo_sources | while IFS= read -r path; do
        [ -f "$ROOT/$path" ] && [ ! -L "$ROOT/$path" ] || fail "invalid source: $path"
        [ "$(wc -c < "$ROOT/$path")" -le "$source_max" ] || fail "oversize source: $path"
        mkdir -p "$run/snapshot/$(dirname -- "$path")"
        cp "$ROOT/$path" "$run/snapshot/$path"
        (cd "$run/snapshot"; shasum -a 256 "$path")
    done > "$run/snapshot/sources.sha256"
    for path in pins.sh host.sh cleanup.sh; do
        cp "$HERE/$path" "$run/control/$path"
        (cd "$run/control"; shasum -a 256 "$path")
    done > "$run/control/controls.sha256"
    printf '%s\n' "$nonce" > "$run/nonce"
    printf '%s\n' "$mode" > "$run/mode"
    date -u '+%Y-%m-%dT%H:%M:%SZ' > "$run/prepared-utc"
    manifest > "$run/manifest"
    printf 'prepared: %s\n' "$run"
}
shell_quote() {
    printf "'"
    printf '%s' "$1" | sed "s/'/'\\\\''/g"
    printf "'"
}
bundle() {
    for assignment in "home=$REMOTE_HOME" "toolchain=$TOOLCHAIN" "compiler=$COMPILER" \
        "archive=$ARCHIVE" "archive_sha=$ARCHIVE_SHA" "compiler_sha=$COMPILER_SHA" \
        "runtime_libraries=${RUNTIME_LIBRARIES:-}"; do
        printf '%s=' "${assignment%%=*}"
        shell_quote "${assignment#*=}"
        printf '\n'
    done
    printf 'cleanup_code='
    shell_quote "$(cat "$run/control/cleanup.sh")"
    printf '\nsource_names='
    shell_quote "$(source_list)"
    printf '\n'
    cat "$run/control/host.sh"
}
transport() {
    remote_command="PATH=/usr/bin:/bin /bin/sh -c $(shell_quote "$(bundle)") sh"
    remote_command="$remote_command $(shell_quote "$1") $(shell_quote "$nonce") $(shell_quote "$mode")"
    ssh -T -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=5 \
        -o ServerAliveCountMax=2 -- hetzner-hel "$remote_command"
}
load() {
    [ -d "$run" ] && [ ! -L "$run" ] || fail 'invalid local run directory'
    nonce=$(cat "$run/nonce")
    mode=$(cat "$run/mode")
    set_names
    (cd "$run/control"; shasum -a 256 -c controls.sha256) >/dev/null
    (cd "$run/snapshot"; shasum -a 256 -c sources.sha256) >/dev/null
    # The source snapshot, not later repo edits, owns this run's exact constants.
    # shellcheck disable=SC1091
    . "$run/control/pins.sh"
    manifest | cmp - "$run/manifest" || fail 'manifest mismatch'
}
upload() {
    set -f
    old_ifs=$IFS
    IFS='
'
    # shellcheck disable=SC2046
    set -- $(source_list) sources.sha256
    IFS=$old_ifs
    tar -cf "$run/upload.tar" -C "$run/snapshot" -- "$@"
    transport upload < "$run/upload.tar"
}
collect() {
    [ ! -e "$run/evidence.tar" ] || fail 'evidence already collected; refusing overwrite'
    if transport collect > "$run/evidence.partial.tar"; then
        mv "$run/evidence.partial.tar" "$run/evidence.tar"
    else
        printf 'FAIL: evidence collection failed or lease expired\n' > "$run/collection-failure.txt"
        fail 'collection failed; partial stream retained; guard remains armed'
    fi
    status=0
    python3 -I -B "$HERE/collect.py" "$run/evidence.tar" \
        "$run/snapshot/sources.sha256" "$run/evidence" "$nonce" "$mode" || status=$?
    if [ -f "$run/evidence/.collection-verified" ] &&
        [ "$(cat "$run/evidence/.collection-verified")" = "$nonce" ]; then
        printf 'collected and locally hashed\n' > "$run/collection-complete"
    fi
    return "$status"
}
[ "$#" -ge 2 ] || fail 'usage: run.sh prepare DIR NONCE MODE | COMMAND DIR'
command=$1
run=$2
case "$run" in /*) ;; *) fail 'local run directory must be absolute' ;; esac
case "$command" in
    prepare)
        [ "$#" -eq 4 ] || fail 'prepare requires DIR NONCE MODE'
        nonce=$3
        mode=$4
        set_names
        prepare
        ;;
    preflight|start|upload|work|observe|collect|teardown|reconcile|render)
        [ "$#" -eq 2 ] || fail 'command requires exactly one manifest directory'
        load
        case "$command" in
            render) bundle ;;
            upload) upload ;;
            collect) collect ;;
            preflight|start)
                transport "$command" > "$run/$command.log"
                cat "$run/$command.log"
                grep -E '^(archive|compiler|runtime) ' "$run/$command.log" > "$run/toolchain-initial.txt"
                ;;
            teardown|reconcile)
                transport "$command" > "$run/$command.log"
                cat "$run/$command.log"
                grep -E '^(archive|compiler|runtime) ' "$run/$command.log" > "$run/toolchain-final.txt"
                cmp "$run/toolchain-initial.txt" "$run/toolchain-final.txt" || fail 'borrowed toolchain changed'
                [ -f "$run/collection-complete" ] || fail 'EVIDENCE_LOST: cleaned without verified collection'
                ;;
            *) transport "$command" ;;
        esac
        ;;
    *) fail 'unknown command' ;;
esac
