#!/usr/bin/env sh
set -eu

hook_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$hook_dir/.."

if [ -t 0 ]; then
  push_input=""
else
  push_input=$(cat)
fi

current_branch=$(git rev-parse --abbrev-ref HEAD)
if [ "$current_branch" != "main" ] && [ "$current_branch" != "HEAD" ]; then
  echo "GHNQG_FAIL_0 gate=publication_route branch=$current_branch" >&2
  exit 1
fi

while IFS=' ' read -r local_ref local_sha remote_ref remote_sha; do
  [ -z "$local_ref" ] && continue
  case "$local_ref:$remote_ref" in
    refs/heads/main:refs/heads/main|HEAD:refs/heads/main|refs/tags/*:refs/tags/*)
      ;;
    *)
      echo "GHNQG_FAIL_0 gate=publication_route attempted=$local_ref:$remote_ref" >&2
      exit 1
      ;;
  esac
done <<EOF
$push_input
EOF

commit=$(git rev-parse HEAD)
receipt_root=${GHNQG_RECEIPT_ROOT:-}
if [ -z "$receipt_root" ] && [ -d /Volumes/JZAO/HoloLake/artifacts ]; then
  receipt_root=/Volumes/JZAO/HoloLake/artifacts/hololake-native-quality/receipts
fi
receipt_root=${receipt_root:-${TMPDIR:-/tmp}/hololake-native-quality-receipts}
mkdir -p "$receipt_root"
receipt="$receipt_root/GHNQG-$commit.hldp"

bash scripts/run-hololake-native-quality-gate.sh "$receipt"
grep -Fxq 'result: PASS_100' "$receipt"
echo "GHNQG_PASS_100 receipt=$receipt"
