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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
LABEL="${SOFIIA_LAUNCHD_LABEL:-com.daarion.sofiia}"
DOMAIN="gui/$(id -u)"
LAUNCH_AGENTS_DIR="${HOME}/Library/LaunchAgents"
PLIST_PATH="${LAUNCH_AGENTS_DIR}/${LABEL}.plist"
START_SCRIPT="${ROOT_DIR}/start-daemon.sh"

PORT_VALUE="${PORT:-8002}"
DATA_DIR_VALUE="${SOFIIA_DATA_DIR:-${HOME}/.sofiia/console-data}"
LOG_DIR="${DATA_DIR_VALUE}/logs"
LOG_OUT="${LOG_DIR}/launchd.out.log"
LOG_ERR="${LOG_DIR}/launchd.err.log"
PATH_VALUE="${PATH:-/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin}"

if [ ! -x "${START_SCRIPT}" ]; then
  echo "[sofiia-launchd] missing start script: ${START_SCRIPT}"
  exit 1
fi

mkdir -p "${LAUNCH_AGENTS_DIR}" "${LOG_DIR}" "${DATA_DIR_VALUE}"

cat > "${PLIST_PATH}" <<PLIST
<?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>${LABEL}</string>

  <key>ProgramArguments</key>
  <array>
    <string>${START_SCRIPT}</string>
  </array>

  <key>WorkingDirectory</key>
  <string>${ROOT_DIR}</string>

  <key>RunAtLoad</key>
  <true/>

  <key>KeepAlive</key>
  <true/>

  <key>StandardOutPath</key>
  <string>${LOG_OUT}</string>
  <key>StandardErrorPath</key>
  <string>${LOG_ERR}</string>

  <key>EnvironmentVariables</key>
  <dict>
    <key>PATH</key>
    <string>${PATH_VALUE}</string>
    <key>PYTHONUNBUFFERED</key>
    <string>1</string>
    <key>PORT</key>
    <string>${PORT_VALUE}</string>
    <key>SOFIIA_DATA_DIR</key>
    <string>${DATA_DIR_VALUE}</string>
  </dict>
</dict>
</plist>
PLIST

chmod 644 "${PLIST_PATH}"

launchctl bootout "${DOMAIN}/${LABEL}" >/dev/null 2>&1 || true
launchctl bootstrap "${DOMAIN}" "${PLIST_PATH}"
launchctl enable "${DOMAIN}/${LABEL}" >/dev/null 2>&1 || true
launchctl kickstart -k "${DOMAIN}/${LABEL}"

echo "[sofiia-launchd] installed: ${PLIST_PATH}"
echo "[sofiia-launchd] active label: ${DOMAIN}/${LABEL}"
echo "[sofiia-launchd] logs: ${LOG_OUT} | ${LOG_ERR}"
echo "[sofiia-launchd] check: launchctl print ${DOMAIN}/${LABEL}"
