#!/bin/bash
# Refuse a commit that stages an unattend answer file the linter rejects.
# A bad answer file stops every bay imaged with it at "Windows could not
# parse or process unattend answer file". Enable with:
#   git config core.hooksPath .githooks
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
mapfile -t FILES < <(git diff --cached --name-only --diff-filter=ACMR | grep -iE '(^|/)(Flat)?Unattend[^/]*\.xml$' || true)
[ ${#FILES[@]} -eq 0 ] && exit 0
TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
STAGED=()
for f in "${FILES[@]}"; do
    out="$TMP/$(echo "$f" | tr '/' '_')"
    git show ":$f" > "$out"     # lint what is staged, not the working copy
    STAGED+=("$out")
done
if ! python3 "$ROOT/scripts/lint-unattend.py" --local "${STAGED[@]}"; then
    echo "pre-commit: unattend lint failed for: ${FILES[*]}" >&2
    exit 1
fi
