#!/bin/sh
BASE="${1:-${PUMDOCTRINE_BASE:-https://pumdoctrine.com}}"
TMP=$(mktemp -d) || exit 1
trap 'rm -rf "$TMP"' EXIT
cd "$TMP" || exit 1
BAD=0
fetch() {
  curl -fsSL --max-time 30 "$BASE/$1" -o "$1" 2>/dev/null || {
    echo "DOWNLOAD FAILED: $1"; BAD=1; return 1
  }
}
fetch PUBLIC-MANIFEST.json
fetch PUBLIC-MANIFEST.sig
fetch public-key.pem
fetch verify.sh
grep -oE '"[^"]+": "[0-9a-f]{64}"' PUBLIC-MANIFEST.json \
  | sed 's/"//g; s/: / /' | grep -v '^manifest_sha256 ' > pairs
while read -r f h; do
  case "$f" in
    /*|*..*) echo "UNSAFE PATH SKIPPED: $f"; BAD=1; continue ;;
  esac
  mkdir -p "$(dirname "$f")"
  fetch "$f"
done < pairs
if [ "$BAD" -ne 0 ]; then
  echo "bootstrap download incomplete — verification not run"
  exit 1
fi
VSH=$(grep -oE '"verify\.sh": "[0-9a-f]{64}"' PUBLIC-MANIFEST.json | cut -d'"' -f4)
if [ -z "$VSH" ] || [ "$(sha256sum verify.sh 2>/dev/null | cut -d' ' -f1)" != "$VSH" ]; then
  echo "FAIL  downloaded verify.sh does not match the signed manifest — refusing to run it"
  exit 1
fi
sh verify.sh
RC=$?
exit $RC
