#!/usr/bin/env bash
#
# Submit a macOS .app bundle to Apple for notarization (no waiting)
# Usage: notarize_submit.sh <app_path>
# Outputs: submission_id=<id> to stdout (for GitHub Actions)
#
# Environment variables (required):
#   APPLE_ID - Apple Developer account email
#   APP_SPECIFIC_PASSWORD - App-specific password for notarytool
#   TEAM_ID - Apple Developer Team ID

set -euo pipefail

APP_PATH="$1"

if [ ! -d "$APP_PATH" ]; then
    echo "ERROR: App not found at $APP_PATH" >&2
    exit 1
fi

if [ -z "${APPLE_ID:-}" ] || [ -z "${APP_SPECIFIC_PASSWORD:-}" ] || [ -z "${TEAM_ID:-}" ]; then
    echo "ERROR: Required environment variables not set" >&2
    echo "  APPLE_ID: ${APPLE_ID:-<not set>}" >&2
    echo "  APP_SPECIFIC_PASSWORD: ${APP_SPECIFIC_PASSWORD:+<set>}" >&2
    echo "  TEAM_ID: ${TEAM_ID:-<not set>}" >&2
    exit 1
fi

# Create ZIP for notarization submission
ZIP_PATH="${APP_PATH%.app}.zip"
echo "=== Creating ZIP for notarization: $ZIP_PATH ===" >&2
ditto -c -k --keepParent "$APP_PATH" "$ZIP_PATH"

echo "=== Submitting to Apple for notarization ===" >&2
SUBMIT_OUTPUT=$(xcrun notarytool submit "$ZIP_PATH" \
    --apple-id "$APPLE_ID" \
    --password "$APP_SPECIFIC_PASSWORD" \
    --team-id "$TEAM_ID" 2>&1)

echo "$SUBMIT_OUTPUT" >&2

# Extract submission ID
SUBMISSION_ID=$(echo "$SUBMIT_OUTPUT" | grep "id:" | head -1 | awk '{print $2}')

if [ -z "$SUBMISSION_ID" ]; then
    echo "ERROR: Failed to get submission ID" >&2
    exit 1
fi

# Clean up the zip
rm "$ZIP_PATH"

echo "Submission ID: $SUBMISSION_ID" >&2

# Output for GitHub Actions
echo "submission_id=$SUBMISSION_ID"
