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

# GoingsOn iOS Release Script
# Builds release archive, exports IPA, and uploads to TestFlight
#
# Prerequisites:
#   - Xcode with iOS SDK
#   - Apple Developer account with PLA accepted
#   - App ID registered for com.goingson.app
#   - App Store Connect API credentials in the environment: source
#     ~/.tauri/passwords.env (APPLE_API_KEY_ID / APPLE_API_ISSUER_ID /
#     APPLE_API_KEY_PATH). They are not in this file; see Configuration below.
#
# Usage:
#   ./dist/release-ios.sh              # full flow: build + export + upload
#   ./dist/release-ios.sh --build-only # build archive only, skip upload
#   ./dist/release-ios.sh --upload-only # export + upload existing archive

cd "$(dirname "$0")/.."

# --- Configuration ---
# App Store Connect API credentials come from the environment, never from this
# file: this script is version-controlled and the repo is mirrored publicly.
# Issuer + key id are two thirds of the notary credential (the .p8 is the third),
# so they live in ~/.tauri/passwords.env, which is not in git. Source it first:
#   source ~/.tauri/passwords.env && ./dist/release-ios.sh
API_KEY_ID="${APPLE_API_KEY_ID:?set APPLE_API_KEY_ID -- source ~/.tauri/passwords.env}"
API_ISSUER_ID="${APPLE_API_ISSUER_ID:?set APPLE_API_ISSUER_ID -- source ~/.tauri/passwords.env}"
API_KEY_PATH="${APPLE_API_KEY_PATH:?set APPLE_API_KEY_PATH -- source ~/.tauri/passwords.env}"
ARCHIVE_PATH="src-tauri/gen/apple/build/goingson-desktop_iOS.xcarchive"
EXPORT_DIR="dist/ios"
EXPORT_PLIST="src-tauri/gen/apple/ExportOptions.plist"
PROJECT_YML="src-tauri/gen/apple/project.yml"

# --- Parse args ---
BUILD=true
UPLOAD=true
for arg in "$@"; do
    case "$arg" in
        --build-only)  UPLOAD=false ;;
        --upload-only) BUILD=false ;;
        -h|--help)
            echo "Usage: $0 [--build-only | --upload-only]"
            exit 0
            ;;
    esac
done

# --- Read version from tauri.conf.json ---
VERSION=$(python3 -c "import json; print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
echo "Version: $VERSION"

# --- Sync version to project.yml ---
if grep -q "CFBundleShortVersionString:" "$PROJECT_YML"; then
    sed -i '' "s/CFBundleShortVersionString: .*/CFBundleShortVersionString: $VERSION/" "$PROJECT_YML"
    sed -i '' "s/CFBundleVersion: .*/CFBundleVersion: \"$VERSION\"/" "$PROJECT_YML"
    echo "Synced version $VERSION to $PROJECT_YML"
fi

# --- Verify API key ---
if [ ! -f "$API_KEY_PATH" ]; then
    echo "Error: API key not found at $API_KEY_PATH"
    echo "Set APPLE_API_KEY_PATH to the correct path"
    exit 1
fi

# --- Flatten app icons (App Store rejects alpha) ---
# `cargo tauri ios init` and ad-hoc icon regenerations have re-seeded the
# appiconset with alpha-channel PNGs more than once (v0.3.1 shipped the Tauri
# default logo; v0.3.4 upload first failed with "Invalid large app icon ...
# can't be transparent or contain an alpha channel"). Re-flatten every build
# from media/logo-go-icon.svg so this can't regress silently.
ICON_SVG="media/logo-go-icon.svg"
ICON_OUT="src-tauri/gen/apple/Assets.xcassets/AppIcon.appiconset"
ICON_TMP="$(mktemp -t goingson-icon-XXXXXX).png"
if [ "$BUILD" = true ] && [ -f "$ICON_SVG" ] && [ -d "$ICON_OUT" ]; then
    echo ""
    echo "=== Flattening app icons (no alpha) ==="
    magick -background white -density 600 "$ICON_SVG" \
        -resize 1024x1024 -alpha remove -alpha off "$ICON_TMP"
    icon_pairs=(
        "AppIcon-20x20@1x.png:20"      "AppIcon-20x20@2x.png:40"
        "AppIcon-20x20@2x-1.png:40"    "AppIcon-20x20@3x.png:60"
        "AppIcon-29x29@1x.png:29"      "AppIcon-29x29@2x.png:58"
        "AppIcon-29x29@2x-1.png:58"    "AppIcon-29x29@3x.png:87"
        "AppIcon-40x40@1x.png:40"      "AppIcon-40x40@2x.png:80"
        "AppIcon-40x40@2x-1.png:80"    "AppIcon-40x40@3x.png:120"
        "AppIcon-60x60@2x.png:120"     "AppIcon-60x60@3x.png:180"
        "AppIcon-76x76@1x.png:76"      "AppIcon-76x76@2x.png:152"
        "AppIcon-83.5x83.5@2x.png:167" "AppIcon-512@2x.png:1024"
    )
    for p in "${icon_pairs[@]}"; do
        name="${p%:*}"; size="${p#*:}"
        magick "$ICON_TMP" -resize "${size}x${size}" \
            -background white -alpha remove -alpha off "$ICON_OUT/$name"
    done
    rm -f "$ICON_TMP"
    echo "Flattened 18 icons from $ICON_SVG"
fi

# --- Build ---
if [ "$BUILD" = true ]; then
    echo ""
    echo "=== Building iOS release archive ==="
    APPLE_API_KEY_PATH="$API_KEY_PATH" cargo tauri ios build --export-method app-store-connect
    echo "Archive: $ARCHIVE_PATH"
fi

# --- Upload ---
if [ "$UPLOAD" = true ]; then
    mkdir -p "$EXPORT_DIR"

    # Pick the freshest IPA across both possible locations. Searching only one
    # location (or stopping at `head -1`) has uploaded stale IPAs in the past.
    IPA_PATH=$(find "$EXPORT_DIR" src-tauri/gen/apple/build \
        -name "*.ipa" -type f 2>/dev/null \
        -exec stat -f '%m %N' {} \; \
        | sort -rn | head -1 | cut -d' ' -f2- || true)

    # If the freshest IPA is older than the archive, the archive hasn't been
    # exported yet — export it now.
    if [ -z "$IPA_PATH" ] || [ "$ARCHIVE_PATH" -nt "$IPA_PATH" ]; then
        echo ""
        echo "=== Exporting IPA from archive ==="
        xcodebuild -exportArchive \
            -archivePath "$ARCHIVE_PATH" \
            -exportOptionsPlist "$EXPORT_PLIST" \
            -exportPath "$EXPORT_DIR" \
            -allowProvisioningUpdates \
            -authenticationKeyID "$API_KEY_ID" \
            -authenticationKeyPath "$API_KEY_PATH" \
            -authenticationKeyIssuerID "$API_ISSUER_ID"
        IPA_PATH=$(find "$EXPORT_DIR" -name "*.ipa" -type f \
            -exec stat -f '%m %N' {} \; \
            | sort -rn | head -1 | cut -d' ' -f2- || true)
    fi

    if [ -z "$IPA_PATH" ]; then
        echo "Error: No IPA found after export"
        exit 1
    fi

    echo ""
    echo "=== Uploading to TestFlight ==="
    echo "IPA: $IPA_PATH"
    # altool exits 0 even when it logs "ERROR:" / "Failed to upload" — grep
    # the output to confirm the success banner before declaring victory.
    set +e
    UPLOAD_OUTPUT=$(xcrun altool --upload-app \
        --type ios \
        --file "$IPA_PATH" \
        --apiKey "$API_KEY_ID" \
        --apiIssuer "$API_ISSUER_ID" 2>&1)
    UPLOAD_RC=$?
    set -e
    echo "$UPLOAD_OUTPUT"

    if [ $UPLOAD_RC -ne 0 ] || ! grep -q "UPLOAD SUCCEEDED" <<<"$UPLOAD_OUTPUT"; then
        echo ""
        echo "Error: altool upload failed (exit=$UPLOAD_RC). See output above."
        exit 1
    fi

    echo ""
    echo "Upload complete! Build will appear in TestFlight within ~30 minutes."
    echo "https://appstoreconnect.apple.com/apps"
fi

echo ""
echo "Done. GoingsOn iOS v$VERSION"
