#!/bin/bash
APPDIR="$(cd "$(dirname "$0")" && pwd)"
SERVER="$APPDIR/automater-server"
PLIST="$HOME/Library/LaunchAgents/house.automater.instance.plist"

# install a LaunchAgent so the instance starts on login (idempotent)
if [ ! -f "$PLIST" ]; then
  mkdir -p "$HOME/Library/LaunchAgents"
  cat > "$PLIST" <<AGENT
<?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>Label</key><string>house.automater.instance</string>
  <key>ProgramArguments</key><array><string>$SERVER</string></array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>$HOME/Library/Logs/automater.house.log</string>
  <key>StandardErrorPath</key><string>$HOME/Library/Logs/automater.house.log</string>
</dict></plist>
AGENT
  launchctl unload "$PLIST" 2>/dev/null || true
  launchctl load "$PLIST" 2>/dev/null || true
fi

# if not already listening, start it in the foreground-detached
if ! curl -s -o /dev/null --max-time 1 http://127.0.0.1:8800/api/version; then
  "$SERVER" >/dev/null 2>&1 &
  sleep 1
fi
open "http://127.0.0.1:8800"
