#!/usr/bin/env bash
set -euo pipefail
repo_root=$(git rev-parse --show-toplevel)
script="$repo_root/modules/ci/install-arc.sh"
test_root=$(mktemp -d "${TMPDIR:-/tmp}/arc-install-test.XXXXXX")
trap 'rm -rf "$test_root"' EXIT

for command in helm kubectl; do
  printf '#!/usr/bin/env bash\nexit 0\n' > "$test_root/$command"
  chmod 0755 "$test_root/$command"
done
printf 'github-token-with-newline\n' > "$test_root/token"
chmod 0600 "$test_root/token"

set +e
output=$(cd / && HELM="$test_root/helm" KUBECTL="$test_root/kubectl" \
  GITHUB_CHECKS_TOKEN_PATH="$test_root/token" bash "$script" 2>&1)
rc=$?
set -e
[[ $rc -eq 2 && "$output" == *'no whitespace or trailing newline'* ]] || {
  printf 'install validation failed: rc=%s output=%s\n' "$rc" "$output" >&2
  exit 1
}
printf 'installer cwd/token validation: PASS\n'

# Every manifest in k8s/ must actually be applied by the installer. The apply
# calls name files one by one, so a new manifest is inert until someone adds it
# there — a check that enforces nothing, which is worse than no check at all,
# because the cluster silently lacks it while the repo says otherwise.
missing=()
for manifest in "$repo_root"/modules/ci/k8s/*.yaml; do
  grep -qF "k8s/$(basename "$manifest")" "$script" || missing+=("$(basename "$manifest")")
done
if (( ${#missing[@]} )); then
  printf 'manifests present in modules/ci/k8s but never applied by install-arc.sh: %s\n' "${missing[*]}" >&2
  exit 1
fi
printf 'installer applies every k8s manifest: PASS (%s)\n' "$(ls "$repo_root"/modules/ci/k8s/*.yaml | wc -l)"
