#!/usr/bin/env bash

# Upload xcarchive to TestFlight using App Store Connect API Key
# This replaces the deprecated altool which was removed in Xcode 14+
#
# Uses xcodebuild -exportArchive with destination=upload, which is Apple's
# recommended approach for CI/CD pipelines.

set -euxo pipefail

# Ensure xcodebuild uses Xcode.app, not Command Line Tools
export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer

ARCHIVE_PATH=${1:?Usage: upload_testflight.sh <xcarchive_path> <team_id> <profile_uuid>}
TEAM_ID=${2:?Missing team ID}
PROFILE_UUID=${3:?Missing provisioning profile UUID}

if [ ! -d "$ARCHIVE_PATH" ]; then
    echo "Error: xcarchive not found: $ARCHIVE_PATH"
    exit 1
fi

echo "Uploading to TestFlight: $ARCHIVE_PATH"

# Requires App Store Connect API Key:
# - APP_STORE_CONNECT_API_KEY_ID: Key ID from App Store Connect
# - APP_STORE_CONNECT_API_ISSUER_ID: Issuer ID from App Store Connect
# - APP_STORE_CONNECT_API_KEY_PATH: Path to .p8 private key file
#
# To create an API key:
# 1. Go to https://appstoreconnect.apple.com/access/api
# 2. Click the + button to create a new key
# 3. Give it a name and Admin or App Manager access
# 4. Download the .p8 file (you can only download it once!)
# 5. Note the Key ID and Issuer ID shown on the page

if [ -z "${APP_STORE_CONNECT_API_KEY_ID:-}" ]; then
    echo "Error: APP_STORE_CONNECT_API_KEY_ID environment variable not set"
    echo "Create an API key at https://appstoreconnect.apple.com/access/api"
    exit 1
fi

if [ -z "${APP_STORE_CONNECT_API_ISSUER_ID:-}" ]; then
    echo "Error: APP_STORE_CONNECT_API_ISSUER_ID environment variable not set"
    exit 1
fi

if [ -z "${APP_STORE_CONNECT_API_KEY_PATH:-}" ]; then
    echo "Error: APP_STORE_CONNECT_API_KEY_PATH environment variable not set"
    exit 1
fi

if [ ! -f "$APP_STORE_CONNECT_API_KEY_PATH" ]; then
    echo "Error: API key file not found: $APP_STORE_CONNECT_API_KEY_PATH"
    exit 1
fi

# Create export options plist with upload destination
EXPORT_OPTIONS_PLIST=$(mktemp)
trap "rm -f $EXPORT_OPTIONS_PLIST" EXIT

cat > "$EXPORT_OPTIONS_PLIST" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>destination</key>
    <string>upload</string>
    <key>method</key>
    <string>app-store-connect</string>
    <key>teamID</key>
    <string>$TEAM_ID</string>
    <key>uploadSymbols</key>
    <true/>
    <key>signingStyle</key>
    <string>manual</string>
    <key>signingCertificate</key>
    <string>Apple Distribution: Daniel Crosby (UWJ88DX8WQ)</string>
    <key>provisioningProfiles</key>
    <dict>
        <key>net.eagle0.eagle</key>
        <string>$PROFILE_UUID</string>
    </dict>
</dict>
</plist>
EOF

echo "Export options:"
cat "$EXPORT_OPTIONS_PLIST"

echo "Uploading to App Store Connect..."

# Use xcodebuild to upload with App Store Connect API authentication
xcodebuild -exportArchive \
    -archivePath "$ARCHIVE_PATH" \
    -exportOptionsPlist "$EXPORT_OPTIONS_PLIST" \
    -authenticationKeyPath "$APP_STORE_CONNECT_API_KEY_PATH" \
    -authenticationKeyID "$APP_STORE_CONNECT_API_KEY_ID" \
    -authenticationKeyIssuerID "$APP_STORE_CONNECT_API_ISSUER_ID"

echo "Upload complete! Check App Store Connect for processing status."
echo "The build should appear in TestFlight within 15-30 minutes after processing."
