#!/bin/zsh
set -euo pipefail
VERSION="3.14.1"
NODE_VERSION="22.23.2"
BUNDLE_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PAYLOAD="$BUNDLE_ROOT/Resources/FleetSlatePayload"
ROOT="$HOME/Library/Application Support/FleetSlate Server"
RUNTIME="$ROOT/runtime"
LOG="$ROOT/fleetslate-launcher.log"
URL="http://localhost:4173/office/"
mkdir -p "$ROOT" "$ROOT/data" "$ROOT/media" "$ROOT/documents" "$ROOT/backups" "$RUNTIME"
exec >>"$LOG" 2>&1
print "[$(date -u +%FT%TZ)] FleetSlate launcher $VERSION"

if [[ ! -d "$PAYLOAD" ]]; then
  osascript -e 'display dialog "FleetSlate application resources are incomplete." buttons {"OK"} default button "OK" with icon stop'
  exit 1
fi
rsync -a --delete \
  --exclude data --exclude media --exclude documents --exclude backups --exclude runtime \
  "$PAYLOAD/" "$ROOT/"

ARCH="$(uname -m)"
case "$ARCH" in
  arm64)
    NODE_ARCH="darwin-arm64"
    NODE_SHA="61130f394c1630d211dd50aecc4353d379480f36d3ac913cd85dbba1aed585c6"
    ;;
  x86_64)
    NODE_ARCH="darwin-x64"
    NODE_SHA="58e99022c2ff89395576cc7fd4d98cea24bb68081475d5f88b801ee8729fb026"
    ;;
  *)
    osascript -e 'display dialog "This Mac architecture is not supported by FleetSlate." buttons {"OK"} default button "OK" with icon stop'
    exit 1
    ;;
esac
NODE_BIN="$RUNTIME/node"
CURRENT=""
if [[ -x "$NODE_BIN" ]]; then CURRENT="$($NODE_BIN -p 'process.versions.node' 2>/dev/null || true)"; fi
if [[ "$CURRENT" != "$NODE_VERSION" ]]; then
  TMP="$(mktemp -d -t fleetslate-node)"
  trap 'rm -rf "$TMP"' EXIT
  ARCHIVE="$TMP/node.tar.gz"
  URL_NODE="https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-$NODE_ARCH.tar.gz"
  osascript -e 'display notification "Preparing the secure FleetSlate runtime. This happens once." with title "FleetSlate Office"' || true
  if ! curl --fail --location --retry 3 --connect-timeout 15 --output "$ARCHIVE" "$URL_NODE"; then
    osascript -e 'display dialog "FleetSlate could not download its runtime. Check the internet connection and start FleetSlate again." buttons {"OK"} default button "OK" with icon stop'
    exit 1
  fi
  ACTUAL="$(shasum -a 256 "$ARCHIVE" | awk '{print $1}')"
  if [[ "$ACTUAL" != "$NODE_SHA" ]]; then
    osascript -e 'display dialog "FleetSlate stopped because the downloaded runtime failed its security check." buttons {"OK"} default button "OK" with icon stop'
    exit 1
  fi
  tar -xzf "$ARCHIVE" -C "$TMP" "node-v$NODE_VERSION-$NODE_ARCH/bin/node"
  install -m 755 "$TMP/node-v$NODE_VERSION-$NODE_ARCH/bin/node" "$NODE_BIN"
fi

PLIST="$HOME/Library/LaunchAgents/uk.fleetslate.server.plist"
mkdir -p "$(dirname "$PLIST")"
cat > "$PLIST" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>Label</key><string>uk.fleetslate.server</string>
<key>ProgramArguments</key><array><string>$NODE_BIN</string><string>--no-warnings</string><string>$ROOT/server.js</string></array>
<key>WorkingDirectory</key><string>$ROOT</string>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>ThrottleInterval</key><integer>10</integer>
<key>EnvironmentVariables</key><dict>
  <key>NODE_ENV</key><string>production</string>
  <key>HOST</key><string>127.0.0.1</string>
  <key>PORT</key><string>4173</string>
  <key>DATA_DIR</key><string>$ROOT/data</string>
  <key>MEDIA_DIR</key><string>$ROOT/media</string>
  <key>DOCUMENT_DIR</key><string>$ROOT/documents</string>
  <key>BACKUP_DIR</key><string>$ROOT/backups</string>
  <key>BACKUP_KEEP</key><string>14</string>
  <key>WRITE_JSON_MIRROR</key><string>false</string>
</dict>
<key>StandardOutPath</key><string>$ROOT/fleetslate.log</string>
<key>StandardErrorPath</key><string>$ROOT/fleetslate-error.log</string>
</dict></plist>
PLIST
launchctl bootout "gui/$UID/uk.fleetslate.server" >/dev/null 2>&1 || true
launchctl bootstrap "gui/$UID" "$PLIST" >/dev/null 2>&1 || launchctl load -w "$PLIST" >/dev/null 2>&1 || true
launchctl kickstart -k "gui/$UID/uk.fleetslate.server" >/dev/null 2>&1 || true

for i in {1..60}; do
  curl -fsS "http://127.0.0.1:4173/api/health" >/dev/null 2>&1 && break
  sleep 0.25
done
if ! curl -fsS "http://127.0.0.1:4173/api/health" >/dev/null 2>&1; then
  osascript -e 'display dialog "FleetSlate was installed but its local service did not start. Open ~/Library/Application Support/FleetSlate Server/fleetslate-error.log for details." buttons {"OK"} default button "OK" with icon stop'
  exit 1
fi
if [[ -x "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ]]; then
  exec "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --app="$URL"
elif [[ -x "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge" ]]; then
  exec "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge" --app="$URL"
else
  open "$URL"
fi
