#!/usr/bin/env bash
# harden stage_payload must ship disk-admission.sh where apply.sh installs from.
set -euo pipefail

BUILDBOX="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
APPLY="$BUILDBOX/host-config/apply.sh"
BIN="$BUILDBOX/bin/buildbox"
LIB="$BUILDBOX/lib/disk-admission.sh"
fail=0
check() { [ "$2" = "$3" ] && printf 'ok   %s\n' "$1" || { printf 'FAIL %s\n  want: %s\n  got:  %s\n' "$1" "$3" "$2"; fail=1; }; }

[ -r "$LIB" ] && present=1 || present=0
check "disk-admission.sh exists in buildbox lib" "$present" "1"

if grep -qF '"$HERE/lib/disk-admission.sh"' "$APPLY"; then
  install_from=1
else
  install_from=0
fi
check "apply.sh installs from payload-local lib path" "$install_from" "1"

if grep -qF '../lib/disk-admission.sh' "$APPLY"; then
  legacy=1
else
  legacy=0
fi
check "apply.sh does not reference host-config/../lib" "$legacy" "0"

body="$(sed -n '/^stage_payload/,/^}/p' "$BIN")"
case "$body" in
  *lib/disk-admission.sh*) stages=1 ;;
  *) stages=0 ;;
esac
check "stage_payload copies disk-admission.sh into payload/lib" "$stages" "1"

if grep -qF 'rm -rf "$buf" "$CLAUDE_STAGE"' "$BIN"; then
  raw_claude_cleanup=1
else
  raw_claude_cleanup=0
fi
check "bootstrap does not raw-remove an immutable Claude stage" "$raw_claude_cleanup" "0"

fixture="$(mktemp -d)"
cp -a "$BUILDBOX/host-config" "$fixture/"
chmod 0555 "$fixture/host-config"

payload="$(BUILDBOX_CONFIG=/dev/null bash -c "
  MOD='$BUILDBOX'
  HOSTCFG='$fixture/host-config'
  CEILINGS=\"\$MOD/../workstation/claude/systemd/user-root\"
  # shellcheck disable=SC1091
  . <(sed -n '/^stage_payload/,/^}/p; /^remove_staged_payload/,/^}/p' '$BIN')
  stage_payload
")"
trap 'chmod u+w "$fixture/host-config" 2>/dev/null || true; rm -rf "$payload" "$fixture"' EXIT
if [ -r "$payload/lib/disk-admission.sh" ]; then
  staged=1
else
  staged=0
fi
check "staged payload contains lib/disk-admission.sh" "$staged" "1"

chmod 0555 "$payload/lib"
bash -c "
  . <(sed -n '/^remove_staged_payload/,/^}/p' '$BIN')
  remove_staged_payload '$payload'
"
[ ! -e "$payload" ] && removed=1 || removed=0
check "staged payload cleanup reopens copied read-only directories" "$removed" "1"
payload=""

exit "$fail"
