#!/usr/bin/env bash

# Build iOS Unity player (generates Xcode project)

set -euxo pipefail

# Read Unity version from project file
UNITY_VERSION=$(grep "m_EditorVersion:" src/main/csharp/net/eagle0/clients/unity/eagle0/ProjectSettings/ProjectVersion.txt | head -1 | sed 's/m_EditorVersion: //')

# Use runner-specific build directory if EAGLE0_BUILD_DIR is set, otherwise default
BUILD_BASE="${EAGLE0_BUILD_DIR:-/tmp/eagle0}"

WORKSPACE=$(pwd)
BUILD_PATH=${1:-"${BUILD_BASE}/eagle0iOS"}
LOG_PATH="${BUILD_BASE}/editor_ios.log"

# Generate unique build number from git commit count
# This ensures each build has a unique number for TestFlight
BUILD_NUMBER=$(git rev-list --count HEAD)
echo "Build number (git commit count): $BUILD_NUMBER"

echo "Building protos"
./scripts/build_protos.sh

UNITY_INSTALL_PATH="/Applications/Unity/Hub/Editor"

echo "Building iOS Unity player to: $BUILD_PATH"

mkdir -p "$(dirname "$LOG_PATH")"
mkdir -p "$BUILD_PATH"

# Build iOS player - this generates an Xcode project
# Capture exit code to show log on failure
set +e
${UNITY_INSTALL_PATH}/${UNITY_VERSION}/Unity.app/Contents/MacOS/Unity \
   -nographics \
   -batchmode \
   -quit \
   -executeMethod BuildScript.BuildiOSPlayer \
   -buildPath "$BUILD_PATH" \
   -buildNumber "$BUILD_NUMBER" \
   -logFile "$LOG_PATH" \
   -projectPath "$WORKSPACE/src/main/csharp/net/eagle0/clients/unity/eagle0"
UNITY_EXIT_CODE=$?
set -e

if [ $UNITY_EXIT_CODE -ne 0 ]; then
    echo ""
    echo "Unity build failed with exit code $UNITY_EXIT_CODE"
    echo "=== Unity Editor Log (last 200 lines) ==="
    tail -200 "$LOG_PATH" || echo "Could not read log file at $LOG_PATH"
    echo "=== End of Unity Editor Log ==="
    exit $UNITY_EXIT_CODE
fi

echo "iOS Unity build complete"
echo "Xcode project generated at: $BUILD_PATH"
ls -la "$BUILD_PATH"
