#!/bin/bash
# Double-click this file. It builds "Tap to Sibelius.app" and opens it.
# Nothing stays running in Terminal afterwards.

set -u
cd "$(dirname "$0")" || exit 1

NAME="Tap to Sibelius"
APP="/Applications/$NAME.app"
SRC="./main.swift"
[ -f "$SRC" ] || SRC="./TapToSibeliusApp.swift"

echo ""
echo "Tap to Sibelius"
echo "==============="

if [ ! -f "$SRC" ]; then
  echo "Getting the app source..."
  SRC="/tmp/TapToSibeliusApp.swift"
  if ! curl -fsSL https://tap2sib.lovable.app/TapToSibeliusApp.swift -o "$SRC"; then
    echo "Could not download the app source. Check the internet connection."
    exit 1
  fi
fi

if ! xcode-select -p >/dev/null 2>&1; then
  echo "One time setup: macOS needs its developer tools."
  echo "Click Install in the window that appears, wait for it to finish,"
  echo "then double-click this file again."
  xcode-select --install
  exit 0
fi

# A running copy holds the MIDI port open, so close it first.
osascript -e 'tell application "Tap to Sibelius" to quit' >/dev/null 2>&1
pkill -x "Tap to Sibelius" >/dev/null 2>&1

echo "Building..."
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" || exit 1

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>Tap to Sibelius</string>
  <key>CFBundleDisplayName</key><string>Tap to Sibelius</string>
  <key>CFBundleExecutable</key><string>TapToSibelius</string>
  <key>CFBundleIdentifier</key><string>app.lovable.tap2sib</string>
  <key>CFBundleVersion</key><string>1.0</string>
  <key>CFBundleShortVersionString</key><string>1.0</string>
  <key>CFBundlePackageType</key><string>APPL</string>
  <key>LSMinimumSystemVersion</key><string>13.0</string>
  <key>LSUIElement</key><true/>
  <key>NSHighResolutionCapable</key><true/>
</dict>
</plist>
PLIST

if ! swiftc -O "$SRC" -o "$APP/Contents/MacOS/TapToSibelius"; then
  echo "Build failed. Send me the message above."
  exit 1
fi

# Ad-hoc signature keeps a stable identity, so the Accessibility permission
# survives rebuilds. It is not Apple notarization.
codesign --force --sign - "$APP" >/dev/null 2>&1
xattr -dr com.apple.quarantine "$APP" >/dev/null 2>&1

echo "Built: $APP"
open "$APP"
echo ""
echo "Look for the small note icon in the menu bar at the top right."
echo "Allow keyboard access when macOS asks, then turn on Launch at login."
echo "You can close this Terminal window now."
