#!/bin/bash
# Launcher script: copies the binary to /tmp (yao-pkg can't write its snapshot
# cache from inside a read-only .app bundle) then opens it in a Terminal window.
# Avoids osascript inline quoting problems by writing the AppleScript to a temp file.

DIR="$(cd "$(dirname "$0")" && pwd)"
BINARY="$DIR/adaptorex-bin"

RUNDIR="$(mktemp -d /tmp/adaptorex-run-XXXXXX)"
cp "$BINARY" "$RUNDIR/adaptorex"
chmod +x "$RUNDIR/adaptorex"

# Write AppleScript to a temp file to avoid inline quoting issues
ASCRIPT="$(mktemp /tmp/adaptorex-launch-XXXXXX.applescript)"
cat > "$ASCRIPT" << 'APPLESCRIPT'
on run argv
  set rundir to item 1 of argv
  set userargs to ""
  repeat with i from 2 to count of argv
    set userargs to userargs & " " & item i of argv
  end repeat
  tell application "Terminal"
    activate
    do script (rundir & "/adaptorex" & userargs & "; EXIT=$?; echo; echo '--- adaptorex exited with code '$EXIT' ---'; read -p 'Press enter to close...'; rm -rf " & rundir)
  end tell
end run
APPLESCRIPT

osascript "$ASCRIPT" "$RUNDIR" "$@"
rm -f "$ASCRIPT"