#!/bin/sh
# Local, Actions-free gate: install with `sh kit/ci/install_hook.sh`. Fails the push when a script,
# catalogue asset or recipe lacks its inventory / recipe / catalogue entry, or when the public-export
# scan of HEAD fails (host names, secrets, personal records, assets without a licence record).
# KIT_PREPUSH_EXPORT=0 skips the export scan (about 6 s) for one push.
root=$(git rev-parse --show-toplevel) || exit 1
py=$(command -v python3 || command -v python)
"$py" "$root/kit/ci/check_entries.py" --root "$root" || exit 1
[ "${KIT_PREPUSH_EXPORT:-1}" = 0 ] && exit 0
out=$(mktemp -d "${TMPDIR:-/tmp}/kit-prepush-export.XXXXXX") || exit 1
log=$("$py" "$root/tools/export_public.py" --src "$root" --rev HEAD --out "$out" 2>&1); rc=$?
rm -rf "$out"
if [ $rc -ne 0 ]; then
  # findings when the scan ran; otherwise (a crash, a bad rules file) the exporter's last lines
  printf '%s\n' "$log" | grep -E '^(FAIL|EXPORT_FAILED)' >&2 || printf '%s\n' "$log" | tail -n 15 >&2
  echo "pre-push: export scan failed (tools/export_public.py); fix the findings above, then push again" >&2
  exit 1
fi
echo "pre-push: export scan OK"
