#!/bin/bash
# Stage an already signed and notarized KillBar app for the npm release.
set -euo pipefail
if [ "$#" -ne 3 ]; then
  echo 'Usage: package-killbar-macos.sh <signed-app> <expected-team-id> <output-zip>' >&2
  exit 2
fi
app=$1
team=$2
output=$3
if [[ ! "$team" =~ ^[A-Z0-9]{10}$ ]] || [[ "$app" != /* ]] || [[ "$output" != /* ]]; then
  echo 'Use absolute paths and the expected 10-character Apple team ID.' >&2
  exit 2
fi
if [ ! -d "$app" ] || [ -e "$output" ]; then
  echo 'The source app must exist and the output must not already exist.' >&2
  exit 1
fi
requirement="=identifier \"ai.slaunt.killbar\" and anchor apple generic and certificate leaf[subject.OU] = \"$team\""
/usr/bin/codesign --verify --deep --strict -R "$requirement" "$app"
/usr/sbin/spctl --assess --type execute "$app"
/usr/bin/xcrun stapler validate "$app"
tmp=$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/slaunt-killbar-release.XXXXXXXX")
trap 'rm -rf "$tmp"' EXIT
/usr/bin/codesign -d --entitlements :- "$app" > "$tmp/entitlements.plist" 2>/dev/null
expected="$team.ai.slaunt.killbar"
actual=$(/usr/libexec/PlistBuddy -c 'Print :com.apple.application-identifier' "$tmp/entitlements.plist")
group=$(/usr/libexec/PlistBuddy -c 'Print :keychain-access-groups:0' "$tmp/entitlements.plist")
if [ "$actual" != "$expected" ] || [ "$group" != "$expected" ]; then
  echo 'The signed application identifier or Keychain access group does not match.' >&2
  exit 1
fi
/usr/bin/ditto "$app" "$tmp/SlauntKillBar.app"
/usr/bin/codesign --verify --deep --strict -R "$requirement" "$tmp/SlauntKillBar.app"
/usr/bin/ditto -c -k --sequesterRsrc --keepParent "$tmp/SlauntKillBar.app" "$tmp/SlauntKillBar.zip"
# Exclusive creation prevents overwriting an existing release artifact.
( set -o noclobber; cat "$tmp/SlauntKillBar.zip" > "$output" )
echo 'Verified KillBar archive created.'
