#!/bin/bash
#
# build.sh — compile HelloVisionOS for the visionOS Simulator
# - Niall George Horn; June 2026

# Info: 
# Targets the xrsimulator SDK, arm64 (Apple Silicon Mac).
# Build products go to <repo>/build/ — relative to the repo root,
# no hardcoded paths, works on any machine.
# I removed aliases from the Tribunal demo. 
# 
# Usage:
#   ./deploy/build.sh
#
# No arguments needed. Just run it from anywhere in the repo.
# No version needed (this is defined in setup.sh)
# Make sure setup.sh has been run first so /tmp/CoreIK.framework exists.


set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
REPO_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"

# Setup Colour formatting 
RED='\033[0;31m'; GREEN='\033[0;32m'; CYAN='\033[0;36m'; BOLD='\033[1m'; RESET='\033[0m'
ok()   { echo -e "${GREEN}  ✅ $*${RESET}"; }
fail() { echo -e "${RED}  ❌ $*${RESET}"; exit 1; }
info() { echo -e "${CYAN}  ℹ  $*${RESET}"; }

echo ""
echo -e "${BOLD}${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}"
echo -e "${BOLD}  Persona_CoreIKDemo — Build (xrsimulator)${RESET}"
echo -e "${BOLD}${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}"
echo ""

# We're gonna build a wall...ed garden! 
if [ ! -f "/tmp/CoreIK.framework/BUILD" ]; then
    fail "/tmp/CoreIK.framework not found — run ./deploy/setup.sh first"
fi
BUILD_TAG=$(cat /tmp/CoreIK.framework/BUILD)
info "CoreIK build: ${BUILD_TAG}"

info "Building HelloVisionOS for xrsimulator..."
set -o pipefail
xcodebuild \
    -project "${REPO_DIR}/HelloVisionOS.xcodeproj" \
    -scheme "HelloVisionOS" \
    -sdk xrsimulator \
    -configuration Debug \
    -destination "generic/platform=xrOS Simulator" \
    SYMROOT="${REPO_DIR}/build" \
    CODE_SIGN_IDENTITY="-" \
    CODE_SIGNING_REQUIRED=NO \
    CODE_SIGNING_ALLOWED=NO \
    | grep -E "error:|warning:|BUILD (SUCCEEDED|FAILED)|Compiling|Linking|note:"

APP_PATH=$(find "${REPO_DIR}/build" -name "HelloVisionOS.app" -path "*xrsimulator*" 2>/dev/null | head -1)
[ -n "$APP_PATH" ] || fail "Build failed — .app not found under ${REPO_DIR}/build"

echo ""
ok "Build succeeded: ${APP_PATH}"
echo ""
echo -e "  Next: ${CYAN}./deploy/launch.sh${RESET}"
echo ""
echo -e "${BOLD}${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}"
echo ""
