#!/usr/bin/env bash
# Gate logic only — contacts no host.
set -uo pipefail

HERE="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
. "$HERE/../lib/fleet-guard.sh"

TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
FLEET_LEDGER="$TMP/ledger.jsonl"
pass=0; fail=0
ok()   { pass=$((pass+1)); printf 'ok   %s\n' "$1"; }
bad()  { fail=$((fail+1)); printf 'FAIL %s\n' "$1"; }
check(){ if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (want=$3 got=$2)"; fi; }

mkdir -p "$TMP/payload/systemd-system"
printf 'Port 2222\n' >"$TMP/payload/sshd.conf"
printf 'x\n' >"$TMP/payload/systemd-system/a.conf"
A="$(fleet_change_id "$TMP/payload")"
B="$(fleet_change_id "$TMP/payload")"
check "change id is stable" "$A" "$B"

cp -a "$TMP/payload" "$TMP/payload2"
check "change id is content-addressed, not path-addressed" "$(fleet_change_id "$TMP/payload2")" "$A"

printf 'ListenAddress 100.64.0.1\n' >>"$TMP/payload2/sshd.conf"
[ "$(fleet_change_id "$TMP/payload2")" != "$A" ] && ok "a changed byte is a different change" || bad "a changed byte is a different change"

chmod 0600 "$TMP/payload2/sshd.conf"
printf 'Port 2222\n' >"$TMP/payload2/sshd.conf"
[ "$(fleet_change_id "$TMP/payload2")" != "$A" ] && ok "mode is part of the change" || bad "mode is part of the change"

fleet_gate_fanout "$A" debian1 >/dev/null 2>&1
check "first host is allowed" "$?" "0"

fleet_ledger_record "$A" debian1 applied
fleet_gate_fanout "$A" debian1 >/dev/null 2>&1
check "re-applying to the host that already carries it is allowed" "$?" "0"

fleet_gate_fanout "$A" debian2 >/dev/null 2>&1
check "second host is refused with no reboot proof" "$?" "1"

fleet_gate_fanout "ffffffffffffffff" debian2 >/dev/null 2>&1
check "an unrelated change is not blocked by this one" "$?" "0"

fleet_ledger_record "$A" debian1 reboot-proven '{"bootIdBefore":"a","bootIdAfter":"b"}'
fleet_gate_fanout "$A" debian2 >/dev/null 2>&1
check "second host is allowed once one host rebooted on it" "$?" "0"

printf 'garbage not json\n' >>"$FLEET_LEDGER"
fleet_gate_fanout "$A" debian3 >/dev/null 2>&1
check "a corrupt ledger line does not break the gate" "$?" "0"

fleet_second_door somehost user 22 >/dev/null 2>&1
check "port 22 fleet sshd cannot prove an independent door" "$?" "1"

fleet_second_door no-such-host-in-any-tailnet user 2222 >/dev/null 2>&1
check "a host with no tailnet address is refused" "$?" "1"

printf '\n%d passed, %d failed\n' "$pass" "$fail"
[ "$fail" = 0 ]
