#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
APP_NAME="${APP_NAME:-$(basename "$ROOT_DIR")}"
APP_PATH="$ROOT_DIR/${APP_NAME}.app"

if ! command -v osacompile >/dev/null 2>&1; then
  echo "Error: osacompile is not available on this macOS installation." >&2
  exit 1
fi

ESCAPED_ROOT="${ROOT_DIR//\"/\\\"}"
SCRIPT_FILE="$(mktemp)"

cat > "$SCRIPT_FILE" <<EOF
on run
    tell application "Terminal"
        activate
        do script "cd \"$ESCAPED_ROOT\" && ./run.sh"
    end tell
end run
EOF

rm -rf "$APP_PATH"
osacompile -o "$APP_PATH" "$SCRIPT_FILE"
rm -f "$SCRIPT_FILE"

echo "Created: $APP_PATH"
echo "You can drag ${APP_NAME}.app into /Applications if desired."
