#!/usr/bin/env bash
# sign.sh - sign (and optionally notarize) an app from silicondevkit.com on your own Mac.
# Usage: ./sign.sh [YourApp.app]    (run it in the folder that contains the app)
set -euo pipefail

APP="${1:-}"
if [ -z "$APP" ]; then
  APP="$(ls -d ./*.app 2>/dev/null | head -n 1 || true)"
  APP="${APP#./}"
fi
if [ -z "$APP" ] || [ ! -d "$APP" ]; then
  echo "Could not find an .app here. Run this in the folder that contains your app,"
  echo "or pass the app: ./sign.sh YourApp.app"
  exit 1
fi

echo "App: $APP"
echo
echo "  1) Sign and notarize for sharing (needs a paid Apple Developer account)"
echo "  2) Just run it on this Mac (testing only, no Apple account needed)"
echo
read -r -p "Choose 1 or 2: " choice

if [ "$choice" = "2" ]; then
  xattr -cr "$APP"
  codesign --force --deep --sign - "$APP"
  echo "Done. You can open $APP on this Mac now."
  exit 0
fi

CERT="$(security find-identity -v -p codesigning | grep "Developer ID Application" | head -n 1 | awk -F'"' '{print $2}' || true)"
if [ -z "$CERT" ]; then
  echo "No \"Developer ID Application\" certificate found in your Keychain."
  echo "Create one at developer.apple.com (Certificates, Identifiers & Profiles),"
  echo "install it, and run this again. Or choose option 2 to test locally."
  exit 1
fi
echo "Signing with: $CERT"

codesign --force --deep --options runtime --timestamp --sign "$CERT" "$APP"

ZIP="${APP%.app}-notarize.zip"
ditto -c -k --keepParent "$APP" "$ZIP"

read -r -p "Notary keychain profile name [AC_PASSWORD]: " PROFILE
PROFILE="${PROFILE:-AC_PASSWORD}"

echo "Submitting to Apple. This usually takes 1-5 minutes..."
xcrun notarytool submit "$ZIP" --keychain-profile "$PROFILE" --wait
rm -f "$ZIP"

xcrun stapler staple "$APP"
spctl --assess --type execute --verbose "$APP" || true
echo "Done. $APP is signed and notarized."
