#!/usr/bin/env bash
#
# Wait for Apple notarization to complete and staple the ticket
# Usage: notarize_wait.sh <submission_id> <app_path>
#
# 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

SUBMISSION_ID="$1"
APP_PATH="$2"

if [ -z "$SUBMISSION_ID" ]; then
    echo "ERROR: submission_id is required" >&2
    exit 1
fi

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
    exit 1
fi

echo "=== Waiting for notarization of submission $SUBMISSION_ID ==="
WAIT_OUTPUT=$(xcrun notarytool wait "$SUBMISSION_ID" \
    --apple-id "$APPLE_ID" \
    --password "$APP_SPECIFIC_PASSWORD" \
    --team-id "$TEAM_ID" 2>&1) || true

echo "$WAIT_OUTPUT"

# Extract status (look for "  status:" to avoid matching "Current status:")
STATUS=$(echo "$WAIT_OUTPUT" | grep "^  status:" | awk '{print $2}')

echo "Status: $STATUS"

if [ "$STATUS" != "Accepted" ]; then
    echo "=== Notarization failed! Fetching log for details ==="
    xcrun notarytool log "$SUBMISSION_ID" \
        --apple-id "$APPLE_ID" \
        --password "$APP_SPECIFIC_PASSWORD" \
        --team-id "$TEAM_ID"
    exit 1
fi

echo "=== Verifying code signature before stapling ==="
if ! codesign --verify --deep --strict "$APP_PATH" 2>&1; then
    echo "ERROR: Code signature verification failed - app may have been damaged during transfer"
    echo "Attempting to show signature details:"
    codesign -dvvv "$APP_PATH" 2>&1 || true
    exit 1
fi
echo "Code signature verified successfully"

echo "=== Stapling notarization ticket to app ==="
# Retry stapling - Apple's CloudKit can take several minutes to propagate the ticket
MAX_STAPLE_ATTEMPTS=10
STAPLE_WAIT_SECONDS=30
STAPLE_ATTEMPT=1
while [ $STAPLE_ATTEMPT -le $MAX_STAPLE_ATTEMPTS ]; do
    echo "Stapling attempt $STAPLE_ATTEMPT/$MAX_STAPLE_ATTEMPTS..."
    if STAPLE_OUTPUT=$(xcrun stapler staple "$APP_PATH" 2>&1); then
        echo "$STAPLE_OUTPUT"
        echo "Stapling successful"
        break
    fi
    echo "Stapler output: $STAPLE_OUTPUT"
    if [ $STAPLE_ATTEMPT -eq $MAX_STAPLE_ATTEMPTS ]; then
        echo "ERROR: Stapling failed after $MAX_STAPLE_ATTEMPTS attempts (total wait: $((MAX_STAPLE_ATTEMPTS * STAPLE_WAIT_SECONDS)) seconds)"
        exit 1
    fi
    echo "Stapling failed, waiting $STAPLE_WAIT_SECONDS seconds before retry..."
    sleep $STAPLE_WAIT_SECONDS
    STAPLE_ATTEMPT=$((STAPLE_ATTEMPT + 1))
done

echo "=== Verifying notarization ==="
xcrun stapler validate "$APP_PATH"
spctl --assess --type exec -v "$APP_PATH"

echo "Notarization complete: $APP_PATH"
