#!/usr/bin/env bash
# Verify a release Mugi.app (or .zip) will pass Sparkle's codesign check.
# Run before uploading to GitHub Releases.
set -euo pipefail

INPUT="${1:?usage: $0 path/to/Mugi.app or Mugi.zip}"

cleanup() {
  [[ -n "${TMP:-}" && -d "$TMP" ]] && rm -rf "$TMP"
}
trap cleanup EXIT

if [[ "$INPUT" == *.zip ]]; then
  TMP="$(mktemp -d)"
  ditto -x -k "$INPUT" "$TMP"
  APP="$(find "$TMP" -name '*.app' -type d | head -1)"
else
  APP="$INPUT"
fi

if [[ -z "$APP" || ! -d "$APP" ]]; then
  echo "FAIL: no .app found in $INPUT" >&2
  exit 1
fi

echo "== Bundle: $APP"

PYCACHE_COUNT="$(find "$APP" -type d -name '__pycache__' | wc -l | tr -d ' ')"
if [[ "$PYCACHE_COUNT" != "0" ]]; then
  echo "FAIL: found ${PYCACHE_COUNT} __pycache__ dirs (Python ran after signing?)." >&2
  find "$APP" -type d -name '__pycache__' | head -20 >&2
  echo "Fix: delete __pycache__, re-sign, re-notarize, re-zip. See docs/release_checklist.md." >&2
  exit 1
fi

echo "== codesign --verify --deep --strict"
codesign --verify --deep --strict --verbose=2 "$APP"
echo "VERIFY_RELEASE_BUNDLE_OK"
