#!/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"

payload="$(BUILDBOX_CONFIG=/dev/null bash -c "
  MOD='$BUILDBOX'
  HOSTCFG=\"\$MOD/host-config\"
  CEILINGS=\"\$MOD/../workstation/claude/systemd/user-root\"
  # shellcheck disable=SC1091
  . <(sed -n '/^stage_payload/,/^}/p' '$BIN')
  stage_payload
")"
trap 'rm -rf "$payload"' 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"

exit "$fail"
