#!/usr/bin/env bash
set -uo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SEAT="$(dirname "$HERE")"
ROOT="$(cd "$SEAT/../../.." && pwd)"
WORK="$(mktemp -d)"
PASS=0
FAIL=0
ok() { PASS=$((PASS+1)); printf '  ok   %s\n' "$1"; }
bad() { FAIL=$((FAIL+1)); printf '  FAIL %s\n     %s\n' "$1" "$2"; }
trap 'rm -rf "$WORK"' EXIT

# ---------------------------------------------------------------- controller material contract
node --input-type=module - "$SEAT" "$WORK" <<'NODE' >"$WORK/node.out" 2>"$WORK/node.err"
import assert from "node:assert/strict";
import { chmodSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
const [seat, work] = process.argv.slice(2);
const m = await import(pathToFileURL(join(seat, "seat-creds.mjs")));
const routeId = "RouteFixture1234567890";
const grantId = "GrantFixture1234567890";
const grantPath = join(work, "proxy.key");
writeFileSync(grantPath, "fixture-proxy-key-with-no-whitespace"); chmodSync(grantPath, 0o600);
const receipt = m.authorityInputManifest({
  provider: "codex", authorityName: "subrouter-primary", routeId, grantId,
  grantExpiresAt: new Date(Date.now()+600_000).toISOString(),
});
assert.equal(receipt.authority_mode, "subrouter");
assert.deepEqual(receipt.materialized_inputs, ["route_id", "proxy_grant"]);
assert.equal(receipt.provider_refresh_token_present, false);
assert.equal(receipt.provider_credential_file_present, false);
assert.equal(receipt.authority_admin_credential_present, false);
assert.equal(receipt.remote_grant_file_removed, false);
assert.equal(receipt.route_id_fingerprint.length, 12);
assert.equal(receipt.grant_id_fingerprint.length, 12);
assert.equal(JSON.stringify(receipt).includes(routeId), false);
assert.equal(JSON.stringify(receipt).includes(grantId), false);
let delivered = null;
const transport = { ssh: (_cfg, command, opts) => { delivered = { command, input: Buffer.from(opts.input) }; return { status: 0, stdout: "" }; } };
const prefix = ".rb/authority-grants/run-123";
const after = m.deliverAuthorityGrant({
  transport, baseConfig: {}, host: "debian1", localGrantPath: grantPath,
  remoteMaterialPrefix: prefix, routeId, receipt,
});
assert.equal(after.authority_mode, "subrouter");
assert.ok(delivered.command.includes("authority-grants"));
assert.equal(delivered.command.includes(routeId), false, "route id never enters remote command argv");
assert.equal(delivered.command.includes("auth.json"), false);
assert.equal(delivered.command.includes(".credentials.json"), false);
assert.equal(delivered.input.toString(), `${routeId}\nfixture-proxy-key-with-no-whitespace`);
let removal = null;
transport.ssh = (_cfg, command) => { removal = command; return { status: 0, stdout: "" }; };
assert.equal(m.removeAuthorityGrant({ transport, baseConfig: {}, host: "debian1", remoteMaterialPrefix: prefix }), true);
assert.ok(removal.includes(`${prefix}.route`));
assert.ok(removal.includes(`${prefix}.key`));
const completed = m.completeAuthorityReceipt(receipt, { grantRevokedAt: new Date().toISOString(), remoteGrantFileRemoved: true });
assert.equal(completed.remote_grant_file_removed, true);
assert.match(completed.grant_revoked_at, /Z$/);
NODE
rc=$?
if [[ $rc -eq 0 ]]; then ok "controller delivers only route+grant and completes bounded receipt"; else bad "controller delivers only route+grant and completes bounded receipt" "$(cat "$WORK/node.err")"; fi

# ---------------------------------------------------------------- root grant helper with fake authority
FAKE="$WORK/fake-subrouter"
LOG="$WORK/fake-subrouter.log"
cat >"$FAKE" <<'SH'
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' "$1" >> "${FAKE_SUBROUTER_LOG:?}"
case "$1 $2" in
  "authority-grant create")
    key=''; id=''
    while (($#)); do
      case "$1" in
        --proxy-key-file) key=$2; shift 2;;
        --grant-id-file) id=$2; shift 2;;
        *) shift;;
      esac
    done
    printf '%s' 'fixture-proxy-key-with-no-whitespace' > "$key"
    printf '%s\n' 'GrantFixture1234567890' > "$id"
    chmod 0600 "$key" "$id"
    ;;
  "authority-grant revoke"|"authority-grant remove") ;;
  *) exit 9;;
esac
SH
chmod 0755 "$FAKE"
ROUTE_REF="$WORK/route.ref"
printf '%s\n' 'RouteFixture1234567890' > "$ROUTE_REF"
chmod 0600 "$ROUTE_REF"
mkdir -p "$WORK/helper-root"
export OVERDECK_SUBROUTER_SEAT_TEST_ROOT="$WORK/helper-root"
export OVERDECK_SUBROUTER_BIN="$FAKE"
export OVERDECK_SUBROUTER_SERVICE_USER="$(id -un)"
export FAKE_SUBROUTER_LOG="$LOG"
create_out="$("$ROOT/modules/subrouter/bin/seat-grant" create --run-id run-123 --route-ref "$ROUTE_REF" --ttl-seconds 300 2>"$WORK/helper-create.err")"
create_rc=$?
STAGE="$WORK/helper-root/run/overdeck-subrouter-seat/$(id -u)/run-123"
if [[ $create_rc -eq 0 && -f "$STAGE/proxy.key" && -f "$STAGE/grant.id" \
  && "$(stat -c '%a' "$STAGE/proxy.key")" == 600 && "$(stat -c '%a' "$STAGE/grant.id")" == 600 \
  && "$create_out" != *RouteFixture* && "$create_out" != *GrantFixture* && "$create_out" != *fixture-proxy-key* ]]; then
  ok "root helper stages protected grant without printing identifiers or key"
else
  bad "root helper stages protected grant without printing identifiers or key" "rc=$create_rc out=$create_out err=$(cat "$WORK/helper-create.err")"
fi
revoke_out="$("$ROOT/modules/subrouter/bin/seat-grant" revoke --run-id run-123 2>"$WORK/helper-revoke.err")"
revoke_rc=$?
if [[ $revoke_rc -eq 0 && ! -e "$STAGE" && "$(tr '\n' ' ' < "$LOG")" == *"authority-grant authority-grant"* \
  && "$revoke_out" != *GrantFixture* && "$revoke_out" != *fixture-proxy-key* ]]; then
  ok "root helper revokes, removes, and deletes local staging"
else
  bad "root helper revokes, removes, and deletes local staging" "rc=$revoke_rc out=$revoke_out log=$(cat "$LOG" 2>/dev/null) err=$(cat "$WORK/helper-revoke.err")"
fi
unset OVERDECK_SUBROUTER_SEAT_TEST_ROOT OVERDECK_SUBROUTER_BIN OVERDECK_SUBROUTER_SERVICE_USER FAKE_SUBROUTER_LOG

# ---------------------------------------------------------------- box-side runner materialization contract
REPO="$WORK/repo"
RUNTIME="$REPO/.harness-seat/run/runtime"
mkdir -p "$RUNTIME/seat" "$RUNTIME/wrappers" "$REPO/workspace" "$REPO/logs"
cp "$SEAT/seat-run.sh" "$RUNTIME/seat/seat-run.sh"
cp "$SEAT/seat-entrypoint.sh" "$RUNTIME/seat/seat-entrypoint.sh"
cp "$SEAT/seat-reconcile.sh" "$RUNTIME/seat/seat-reconcile.sh"
cp "$SEAT/credentials.json" "$RUNTIME/seat/credentials.json"
chmod 0755 "$RUNTIME/seat/seat-run.sh" "$RUNTIME/seat/seat-entrypoint.sh" "$RUNTIME/seat/seat-reconcile.sh"
printf '#!/bin/sh\nexit 0\n' > "$RUNTIME/wrappers/codex.sh"; chmod 0755 "$RUNTIME/wrappers/codex.sh"
HOME_FIX="$WORK/home"; mkdir -p "$HOME_FIX/.local/bin" "$HOME_FIX/.rb/authority-grants"
printf '%s\n' 'RouteFixture1234567890' > "$HOME_FIX/.rb/authority-grants/run-123.route"
printf '%s' 'fixture-proxy-key-with-no-whitespace' > "$HOME_FIX/.rb/authority-grants/run-123.key"
chmod 0600 "$HOME_FIX/.rb/authority-grants/run-123.route" "$HOME_FIX/.rb/authority-grants/run-123.key"
CAPTURE="$WORK/podman-create.txt"
cat > "$HOME_FIX/.local/bin/podman" <<'SH'
#!/usr/bin/env bash
case "$1" in
  image) exit 0;;
  run) exit 0;;
  ps) exit 0;;
  create) printf '%s\n' "$@" > "${PODMAN_CAPTURE:?}"; exit 0;;
  start) printf '%s\n' '{"ok":true}'; exit 0;;
  rm) exit 0;;
  *) exit 0;;
esac
SH
chmod 0755 "$HOME_FIX/.local/bin/podman"
printf '#!/bin/sh\nexit 0\n' > "$HOME_FIX/.local/bin/tmux"; chmod 0755 "$HOME_FIX/.local/bin/tmux"
PROMPT="$WORK/prompt"; printf 'fixture prompt\n' > "$PROMPT"
PODMAN_CAPTURE="$CAPTURE" BUILD_REMOTE_INPUT_FILE="$PROMPT" HOME="$HOME_FIX" \
  bash "$RUNTIME/seat/seat-run.sh" \
    --run-id run-123 --wrapper codex.sh --repo-root "$REPO" --workspace-rel workspace \
    --prompt-file ignored --log-rel logs --task-slug authority-probe --image harness-seat:test \
    --memory 1g --cpus 1 --pids 64 --tmpfs-size 64m --max-seats 3 \
    --authority-mode subrouter --authority-origin http://100.126.128.50:31416 \
    --authority-material-rel .rb/authority-grants/run-123 --authority-provider codex \
    --authority-name subrouter-primary --authority-probe-only \
    >"$WORK/runner.out" 2>"$WORK/runner.err"
runner_rc=$?
if [[ $runner_rc -eq 0 && -f "$CAPTURE" \
  && "$(cat "$CAPTURE")" == *'/usr/local/bin/seat-entrypoint.sh:ro'* \
  && "$(cat "$CAPTURE")" == *'/seed/subrouter/route.id:ro'* \
  && "$(cat "$CAPTURE")" == *'/seed/subrouter/proxy.key:ro'* \
  && "$(cat "$CAPTURE")" != *'.codex/auth.json'* \
  && "$(cat "$CAPTURE")" != *'.credentials.json'* \
  && "$(cat "$CAPTURE")" != *'HARNESS_SEAT_CREDENTIALS_MANIFEST'* \
  && "$(cat "$CAPTURE")" != *'RouteFixture1234567890'* \
  && "$(cat "$CAPTURE")" != *'fixture-proxy-key'* \
  && "$(cat "$WORK/runner.err")" != *'RouteFixture1234567890'* \
  && "$(cat "$WORK/runner.err")" != *'fixture-proxy-key'* ]]; then
  ok "authority runner mounts only protected route+grant and redacts create log"
else
  bad "authority runner mounts only protected route+grant and redacts create log" "rc=$runner_rc stderr=$(tail -20 "$WORK/runner.err") capture=$(cat "$CAPTURE" 2>/dev/null)"
fi

echo
echo "PASS=$PASS FAIL=$FAIL"
[[ $FAIL -eq 0 ]]
