# Preamble supplies audited constants and the immutable cleanup body; no file is installed.
set -eu
umask 077
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
[ "$#" -eq 3 ] || fail 'expected COMMAND NONCE MODE'
action=$1
nonce=$2
mode=$3
case "$nonce" in *[!0-9a-f]*|'') fail 'invalid nonce' ;; esac
[ "${#nonce}" -eq 16 ] || fail 'invalid nonce length'
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"
workspace="$home/.pi-c-s0-$nonce"
worker_seconds=300
[ "$mode" != timeout ] || worker_seconds=3
# Must match run.sh's manifest for the mode.
lease_seconds=600
tasks_max=64
memory_max=1G
cpu_quota=100%
upload_blocks=2048
if [ "$mode" = pic ]; then
    worker_seconds=6600
    lease_seconds=7200
    tasks_max=128
    memory_max=2G
    cpu_quota=200%
    upload_blocks=65536
fi
[ "$(id -u)" = 1000 ] && [ "$(id -g)" = 1000 ] || fail 'requires UID/GID1000'
[ "$(getent passwd 1000 | cut -d: -f6)" = "$home" ] || fail 'home differs from audit'
[ ! -L "$home" ] || fail 'home symlink'
[ "$(CDPATH= cd -- "$home" && pwd -P)" = "$home" ] || fail 'noncanonical home'
case "$(stat -c '%u:%g:%a' -- "$home")" in 1000:1000:700|1000:1000:750|1000:1000:755) ;;
    *) fail 'home ownership or mode' ;;
esac
[ ! -L "$workspace" ] || fail 'workspace symlink'

ctl() { sudo -n /usr/bin/systemctl "$@"; }
run_unit() { sudo -n /usr/bin/systemd-run "$@"; }
property() { ctl show "$1" --property="$2" --value; }
no_unit() { [ "$(property "$1" LoadState)" = not-found ]; }
require_workspace() {
    [ -d "$workspace" ] && [ ! -L "$workspace" ] || fail 'EVIDENCE_LOST: workspace absent'
    [ "$(stat -c '%u:%g:%a' -- "$workspace")" = 1000:1000:700 ] || fail 'workspace owner/mode'
    [ "$(CDPATH= cd -- "$workspace" && pwd -P)" = "$workspace" ] || fail 'workspace canonicality'
    marker="$workspace/.pi-c-owner"
    [ -f "$marker" ] && [ ! -L "$marker" ] || fail 'workspace marker absent'
    [ "$(stat -c '%u:%g:%a' -- "$marker")" = 1000:1000:600 ] || fail 'marker owner/mode'
    [ "$(wc -c < "$marker")" -eq 17 ] || fail 'marker size'
    [ "$(cat "$marker")" = "$nonce" ] || fail 'marker mismatch'
}
require_guard() {
    [ "$(property "$timer" ActiveState)" = active ] || fail 'cleanup timer not active'
    [ "$(property "$timer" Unit)" = "$cleanup" ] || fail 'cleanup timer target mismatch'
    next=$(property "$timer" NextElapseUSecMonotonic)
    case "$next" in ''|0|infinity) fail 'cleanup timer has no finite deadline' ;; esac
}
# systemd Exec*= property syntax, not shell syntax. ':' disables $ expansion.
exec_argument() {
    printf '"'
    printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'
    printf '"'
}
cleanup_exec() {
    printf ':/bin/sh -c '
    exec_argument "$cleanup_code"
    printf ' sh '
    exec_argument "$home"
    printf ' '
    exec_argument "$workspace"
    printf ' '
    exec_argument "$nonce"
}
fingerprints() {
    printf 'archive '
    sha256sum -- "$archive"
    printf 'compiler '
    sha256sum -- "$compiler"
    [ -n "$runtime_libraries" ] || fail 'no audited runtime library paths'
    printf '%s\n' "$runtime_libraries" | while IFS= read -r library; do
        case "$library" in "$toolchain"/pizfix/lib/*|"$toolchain"/pizfix/lib64/*) ;;
            *) fail 'runtime path outside audited toolchain runtime directories' ;; esac
        [ -f "$library" ] || fail 'runtime library missing'
        printf 'runtime '
        sha256sum -- "$library"
    done
}
preflight() {
    [ "$(uname -s)" = Linux ] || fail 'Linux required'
    [ "$(uname -m)" = x86_64 ] || fail 'audited x86_64 required'
    [ -x "$compiler" ] && [ -f "$archive" ] || fail 'audited toolchain missing'
    printf '%s  %s\n' "$archive_sha" "$archive" "$compiler_sha" "$compiler" | sha256sum -c -
    systemd-run --help | grep -q -- '--expand-environment' || fail 'systemd >=254 required'
    for unit in "$owner" "$worker" "$cleanup" "$timer"; do
        no_unit "$unit" || fail "unit collision: $unit"
    done
    [ ! -e "$workspace" ] && [ ! -L "$workspace" ] || fail 'workspace collision'
    [ "$mode" != pic ] || [ -x /usr/bin/timeout ] || fail 'coreutils timeout required'
    fingerprints
    "$compiler" --version
    df -Pk "$home"
    printf 'preflight: ready\n'
}
start() {
    preflight
    stop_post=$(cleanup_exec)
    # Arm before the first mkdir. This timer and both service commands live in PID1.
    # Transient exec arguments are already D-Bus values, not unit-file specifiers.
    timer_code=$cleanup_code
    run_unit --quiet --collect --unit="$cleanup" --on-active="${lease_seconds}s" \
        --timer-property=AccuracySec=1s --timer-property=RemainAfterElapse=no \
        --property=Type=oneshot --property=User=1000 --property=Group=1000 \
        --property="Conflicts=$owner $worker" --property="After=$owner $worker" \
        --property=TimeoutStartSec=20s --property=TimeoutStopSec=5s \
        --property=NoNewPrivileges=yes --property=UMask=0077 \
        --expand-environment=no -- /bin/sh -c "$timer_code" sh "$home" "$workspace" "$nonce"
    require_guard
    create_code='set -eu; umask 077; [ ! -e "$1" ] && [ ! -L "$1" ];
mkdir -m 700 -- "$1"; printf "%s\n" "$2" > "$1/.pi-c-owner"'
    create_exec=":/bin/sh -c $(exec_argument "$create_code") sh"
    create_exec="$create_exec $(exec_argument "$workspace") $(exec_argument "$nonce")"
    run_unit --quiet --collect --unit="$owner" --property=Type=exec \
        --property=User=1000 --property=Group=1000 --property=UMask=0077 \
        --property="RuntimeMaxSec=${lease_seconds}s" --property=TimeoutStartSec=10s \
        --property=TimeoutStopSec=5s --property=KillMode=control-group \
        --property="TasksMax=$tasks_max" --property="MemoryMax=$memory_max" --property="CPUQuota=$cpu_quota" \
        --property=LimitFSIZE=134217728 --property=NoNewPrivileges=yes \
        --property="ExecStartPre=$create_exec" --property="ExecStopPost=$stop_post" \
        --expand-environment=no -- /bin/sleep "$lease_seconds"
    [ "$(property "$owner" ActiveState)" = active ] || fail 'owner not active'
    require_guard
    printf 'start: guarded lease active\n'
}
upload() {
    require_guard
    require_workspace
    [ "$(property "$owner" ActiveState)" = active ] || fail 'owner not active'
    [ ! -e "$workspace/.upload-complete" ] || fail 'upload collision'
    # The trusted local sender generates exactly these paths, no project tree upload.
    set -f
    old_ifs=$IFS
    IFS='
'
    # shellcheck disable=SC2086
    set -- $source_names sources.sha256
    IFS=$old_ifs
    (ulimit -f "$upload_blocks"; tar -xf - -C "$workspace" --keep-old-files \
        --no-same-owner --no-same-permissions -- "$@")
    (cd "$workspace"; sha256sum -c sources.sha256)
    fingerprints > "$workspace/toolchain-before.txt"
    printf '%s\n' "$nonce" > "$workspace/.upload-complete"
    printf 'upload: verified\n'
}
work() {
    require_guard
    require_workspace
    [ "$(cat "$workspace/.upload-complete")" = "$nonce" ] || fail 'upload missing'
    no_unit "$worker" || fail 'worker collision'
    [ ! -e "$workspace/.work-started" ] || fail 'worker already started'
    printf '%s\n' "$nonce" > "$workspace/.work-started"
    # PID1 opens append logs before dropping User=; precreate as the run owner.
    [ ! -e "$workspace/worker.log" ] && [ ! -L "$workspace/worker.log" ] || fail 'log collision'
    : > "$workspace/worker.log"
    chmod 600 "$workspace/worker.log"
    # Keep failed worker status available for evidence; teardown resets it later.
    run_unit --quiet --unit="$worker" --property=Type=exec \
        --property=User=1000 --property=Group=1000 --property=UMask=0077 \
        --property="BindsTo=$owner" --property="After=$owner" \
        --property=RemainAfterExit=yes --property="RuntimeMaxSec=${worker_seconds}s" \
        --property=TimeoutStartSec=10s --property=TimeoutStopSec=5s \
        --property=KillMode=control-group --property=SendSIGKILL=yes \
        --property="TasksMax=$tasks_max" --property="MemoryMax=$memory_max" --property="CPUQuota=$cpu_quota" \
        --property=LimitFSIZE=134217728 --property=NoNewPrivileges=yes \
        --property=ProtectSystem=strict --property=ProtectHome=read-only \
        --property=PrivateTmp=yes --property=PrivateNetwork=yes \
        --property="ReadWritePaths=$workspace" --property="ReadOnlyPaths=$toolchain" \
        --property="WorkingDirectory=$workspace" \
        --property="StandardOutput=append:$workspace/worker.log" \
        --property="StandardError=append:$workspace/worker.log" \
        --expand-environment=no -- /bin/sh "$workspace/tools/remote/payload.sh" "$mode" "$compiler"
    printf 'work: launched independently of transport\n'
}
observe() {
    for unit in "$owner" "$worker" "$cleanup" "$timer"; do
        ctl show "$unit" --property=Id,LoadState,ActiveState,SubState,Result,ExecMainCode,ExecMainStatus,\
ControlGroup,RuntimeMaxUSec,TimeoutStopUSec,User,Group,NextElapseUSecMonotonic
    done
    if [ ! -e "$workspace" ]; then fail 'EVIDENCE_LOST: workspace absent'; fi
}
# Read-only progress: worker state plus the log's last lines. Guard and
# workspace identity are checked, nothing is written or stopped.
tail_log() {
    require_guard
    require_workspace
    printf 'worker: %s/%s\n' "$(property "$worker" ActiveState)" "$(property "$worker" SubState)"
    [ -f "$workspace/worker.log" ] && [ ! -L "$workspace/worker.log" ] || fail 'worker log absent'
    printf 'log bytes: %s\n' "$(wc -c < "$workspace/worker.log")"
    # Failures and step timings first: they scroll out of the last lines.
    grep -E '^FAIL|STEP END|PHASE' -- "$workspace/worker.log" | tail -n 12 | sed 's/^/summary: /' || :
    tail -n 40 -- "$workspace/worker.log"
}
collect() {
    require_guard
    require_workspace
    [ "$(property "$worker" SubState)" != running ] || fail 'worker still running'
    [ "$(property "$worker" SubState)" != start ] || fail 'worker still starting'
    [ -f "$workspace/worker.log" ] || fail 'EVIDENCE_LOST: worker log absent'
    observe > "$workspace/supervisor.txt"
    fingerprints > "$workspace/toolchain-after.txt"
    (cd "$workspace"; find . -type f ! -name SHA256SUMS -print | LC_ALL=C sort | \
        while IFS= read -r file; do sha256sum -- "$file"; done > SHA256SUMS
        tar -cf - .)
}
inactive() {
    for unit in "$owner" "$worker" "$cleanup" "$timer"; do
        state=$(property "$unit" ActiveState)
        case "$state" in inactive|failed) ;; *) fail "unit not inactive: $unit ($state)" ;; esac
        group=$(property "$unit" ControlGroup)
        if [ -n "$group" ] && [ -e "/sys/fs/cgroup$group/cgroup.events" ]; then
            grep -qx 'populated 0' "/sys/fs/cgroup$group/cgroup.events" || fail "populated: $unit"
        fi
    done
}
teardown() {
    # Stop worker first; the owner StopPost runs only after worker stop completes.
    for unit in "$worker" "$owner"; do
        if ! no_unit "$unit"; then ctl stop "$unit"; fi
    done
    # Re-run the same cleanup as UID1000 even if the owner never reached ExecStart.
    /bin/sh -c "$cleanup_code" sh "$home" "$workspace" "$nonce"
    [ ! -e "$workspace" ] && [ ! -L "$workspace" ] || fail 'workspace remains'
    if ! no_unit "$cleanup"; then ctl stop "$cleanup"; fi
    # Do not disarm the timer before directory absence is independently checked.
    if ! no_unit "$timer"; then ctl stop "$timer"; fi
    inactive
    for unit in "$worker" "$owner" "$cleanup" "$timer"; do
        if ! no_unit "$unit"; then ctl reset-failed "$unit"; fi
    done
    fingerprints
    printf 'teardown: resources inactive and workspace absent\n'
}
reconcile() {
    inactive
    [ ! -e "$workspace" ] && [ ! -L "$workspace" ] || fail 'workspace remains'
    fingerprints
    printf 'reconcile: clean\n'
}
case "$action" in
    tail) tail_log ;;
    preflight|start|upload|work|observe|collect|teardown|reconcile) "$action" ;;
    *) fail 'invalid action' ;;
esac
