#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CACHE_ROOT="${GPT_REALTIME_MAC_CACHE:-$HOME/Library/Caches/gpt-realtime/macos}"
BUILD_ROOT="$CACHE_ROOT/swift-build"
APP_PATH="$CACHE_ROOT/GPT Realtime.app"
CONTENTS="$APP_PATH/Contents"
export SWIFTPM_MODULECACHE_OVERRIDE="$CACHE_ROOT/swift-module-cache"
export CLANG_MODULE_CACHE_PATH="$CACHE_ROOT/clang-module-cache"

swift build \
  --disable-sandbox \
  --package-path "$SCRIPT_DIR" \
  --scratch-path "$BUILD_ROOT" \
  -c release

BIN_PATH="$(swift build --disable-sandbox --package-path "$SCRIPT_DIR" --scratch-path "$BUILD_ROOT" -c release --show-bin-path)"
mkdir -p "$CONTENTS/MacOS" "$CONTENTS/Resources"
cp "$BIN_PATH/GPTRealtimeMac" "$CONTENTS/MacOS/GPTRealtimeMac"
cp "$SCRIPT_DIR/Resources/Info.plist" "$CONTENTS/Info.plist"
chmod 755 "$CONTENTS/MacOS/GPTRealtimeMac"
codesign --force --sign - "$APP_PATH" >/dev/null

if [[ "${1:-}" == "--build-only" ]]; then
  echo "$APP_PATH"
  exit 0
fi

if [[ "${1:-}" == "--" ]]; then
  shift
fi

open "$APP_PATH" --args "$@"
echo "GPT Realtime is running in the menu bar."
