#!/usr/bin/env bash
set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
IDENTITY="${POLYFORM_CODESIGN_IDENTITY:-}"
if [[ -z "$IDENTITY" ]]; then
    IDENTITY="Developer ID Application: Daniel O'Malley (BTP4V4J2W2)"
fi
NOTARY_PROFILE="${POLYFORM_NOTARY_PROFILE:-derder-notary}"
NOTARY_KEYCHAIN="${POLYFORM_NOTARY_KEYCHAIN:-${HOME}/Library/Keychains/login.keychain-db}"
OUTPUT_DIR="${POLYFORM_MACOS_OUTPUT_DIR:-$PROJECT_ROOT/artifacts/macos-release}"

command -v cargo >/dev/null
command -v codesign >/dev/null
command -v xcrun >/dev/null

if ! security find-identity -v -p codesigning "$NOTARY_KEYCHAIN" | grep -Fq "$IDENTITY"; then
    printf 'No Developer ID Application certificate is available in the login keychain.\n' >&2
    exit 1
fi

cd "$PROJECT_ROOT"
cargo build --release --locked -p polyform-cli

STAGING_DIR="$(mktemp -d "${TMPDIR:-/tmp}/polyform-notarize.XXXXXX")"
trap 'rm -rf "$STAGING_DIR"' EXIT HUP INT TERM
mkdir -p "$OUTPUT_DIR"
install -m 0755 target/release/polyform "$STAGING_DIR/polyform"

codesign --force \
    --sign "$IDENTITY" \
    --identifier com.omalled.polyform.cli \
    --options runtime \
    --timestamp \
    "$STAGING_DIR/polyform"
codesign --verify --strict --verbose=2 "$STAGING_DIR/polyform"

(
    cd "$STAGING_DIR"
    ditto -c -k polyform polyform-aarch64-apple-darwin.zip
)
xcrun notarytool submit "$STAGING_DIR/polyform-aarch64-apple-darwin.zip" \
    --keychain-profile "$NOTARY_PROFILE" \
    --keychain "$NOTARY_KEYCHAIN" \
    --wait

# Command-line executables cannot carry a stapled ticket. Gatekeeper retrieves
# the accepted ticket by the executable's signed code hash when it first runs.
# `spctl` may still say a standalone executable "does not seem to be an app";
# the authoritative checks here are the strict signature verification above and
# the Accepted result returned by Apple's notary service.
spctl --assess --type execute --verbose=2 "$STAGING_DIR/polyform" || true
cp -p "$STAGING_DIR/polyform" "$OUTPUT_DIR/polyform-aarch64-apple-darwin"
cp -p "$STAGING_DIR/polyform-aarch64-apple-darwin.zip" "$OUTPUT_DIR/polyform-aarch64-apple-darwin.zip"
chmod 0644 "$OUTPUT_DIR/polyform-aarch64-apple-darwin.zip"
codesign --verify --strict --verbose=2 "$OUTPUT_DIR/polyform-aarch64-apple-darwin"

printf 'Signed and notarized files written to %s\n' "$OUTPUT_DIR"
