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

# install (or refresh, if the app moved) a LaunchAgent so it starts on login
if [ ! -f "$PLIST" ] || ! grep -q "$SERVER" "$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

# an older server left running from a previous install would keep serving
# stale code (it holds the port, so the new one can't start) — restart it
WANT="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$APPDIR/../Info.plist" 2>/dev/null)"
RUNNING="$(curl -s --max-time 1 http://127.0.0.1:8800/api/version | sed -n 's/.*"version":"\([^"]*\)".*/\1/p')"
if [ -n "$RUNNING" ] && [ "$RUNNING" != "$WANT" ]; then
  launchctl kickstart -k "gui/$(id -u)/house.automater.instance" 2>/dev/null || true
  sleep 1
  RUNNING="$(curl -s --max-time 1 http://127.0.0.1:8800/api/version | sed -n 's/.*"version":"\([^"]*\)".*/\1/p')"
  if [ -n "$RUNNING" ] && [ "$RUNNING" != "$WANT" ]; then
    pkill -f 'automater.house.app/Contents/MacOS/automater-server' 2>/dev/null || true
    sleep 1
  fi
fi

# give the LaunchAgent's copy a few seconds to come up; only start one
# ourselves if it never answers (e.g. launchd refused the agent)
up() { curl -s -o /dev/null --max-time 1 http://127.0.0.1:8800/api/version; }
for _ in 1 2 3 4 5 6 7 8 9 10; do up && break; sleep 0.5; done
if ! up; then
  "$SERVER" >/dev/null 2>&1 &
  for _ in 1 2 3 4 5 6; do up && break; sleep 0.5; done
fi
open "http://127.0.0.1:8800"
