#!/bin/bash
# Builds PokerTutor.app.
#
# Swift Package Manager produces a bare executable, and a Mac app needs to be a bundle to behave
# like one — to own a window, appear in the Dock, and be launched by double-clicking. This wraps
# the built binary in the smallest bundle that does all three. When the iPhone target arrives it
# will come with an Xcode project and this script becomes the Mac-only path.
set -euo pipefail

cd "$(dirname "$0")/.."
CONFIG="${1:-release}"
# Which product: "tournament" (Poker Tutor) or "cash" (Poker Tutor Cash).
PRODUCT="${2:-tournament}"
case "$PRODUCT" in
  tournament) TARGET=PokerTutorApp;     EXE=PokerTutor;     NAME="Poker Tutor";      BID=app.pokertutor.mac ;;
  cash)       TARGET=PokerTutorCashApp; EXE=PokerTutorCash; NAME="Poker Tutor Cash"; BID=app.pokertutor.cash.mac ;;
  *) echo "usage: build-app.sh [debug|release] [tournament|cash]"; exit 1 ;;
esac

swift build -c "$CONFIG" --product "$TARGET"

BIN=".build/$CONFIG/$TARGET"
APP="build/$EXE.app"

rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cp "$BIN" "$APP/Contents/MacOS/$EXE"

cat > "$APP/Contents/Info.plist" <<PLIST
<?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>CFBundleName</key><string>$NAME</string>
    <key>CFBundleDisplayName</key><string>$NAME</string>
    <key>CFBundleExecutable</key><string>$EXE</string>
    <key>CFBundleIdentifier</key><string>$BID</string>
    <key>CFBundleVersion</key><string>1</string>
    <key>CFBundleShortVersionString</key><string>0.1</string>
    <key>CFBundlePackageType</key><string>APPL</string>
    <key>LSMinimumSystemVersion</key><string>14.0</string>
    <key>NSHighResolutionCapable</key><true/>
    <key>NSPrincipalClass</key><string>NSApplication</string>
    <key>LSApplicationCategoryType</key><string>public.app-category.card-games</string>
</dict>
</plist>
PLIST

codesign --force --deep --sign - "$APP" 2>/dev/null || true
echo "Built $APP"
