#!/usr/bin/env bash
# Validate that a macOS provisioning profile authorizes the identity and shared Keychain group
# claimed by Nucleic's distribution signature. Apple enforces these at exec time; codesign's static
# verification does not, so packaging must fail before producing an app that AMFI will kill.
set -euo pipefail

PROFILE="${1:?usage: validate-macos-profile.sh PROFILE BUNDLE_ID ACCESS_GROUP TEAM_ID}"
BUNDLE_ID="${2:?missing bundle id}"
ACCESS_GROUP="${3:?missing access group}"
TEAM_ID="${4:?missing team id}"

[ -f "$PROFILE" ] || { echo "provisioning profile not found: $PROFILE" >&2; exit 1; }
DECODED="$(mktemp "${TMPDIR:-/tmp}/nucleic-profile.XXXXXX.plist")"
trap 'rm -f "$DECODED"' EXIT
security cms -D -i "$PROFILE" > "$DECODED"

profile_team="$(/usr/libexec/PlistBuddy -c 'Print :TeamIdentifier:0' "$DECODED" 2>/dev/null || true)"
[ "$profile_team" = "$TEAM_ID" ] || {
  echo "provisioning profile team '$profile_team' does not match required team '$TEAM_ID'" >&2
  exit 1
}

app_id="$(/usr/libexec/PlistBuddy -c 'Print :Entitlements:com.apple.application-identifier' "$DECODED" 2>/dev/null || true)"
[ -n "$app_id" ] || app_id="$(/usr/libexec/PlistBuddy -c 'Print :Entitlements:application-identifier' "$DECODED" 2>/dev/null || true)"
case "$app_id" in
  "$TEAM_ID."*) authorized_bundle="${app_id#"$TEAM_ID."}" ;;
  *) echo "profile has no application identifier for team $TEAM_ID" >&2; exit 1 ;;
esac
case "$BUNDLE_ID" in
  $authorized_bundle) ;;
  *) echo "profile application identifier '$app_id' does not authorize '$BUNDLE_ID'" >&2; exit 1 ;;
esac

groups="$(/usr/libexec/PlistBuddy -c 'Print :Entitlements:keychain-access-groups' "$DECODED" 2>/dev/null || true)"
if ! printf '%s\n' "$groups" | grep -Fq "$ACCESS_GROUP" \
  && ! printf '%s\n' "$groups" | grep -Fq "$TEAM_ID.*"; then
  echo "profile does not authorize Keychain access group '$ACCESS_GROUP'" >&2
  exit 1
fi
