#!/usr/bin/env bash
# kraken-player macOS installer. Installs the binary + a LaunchAgent that runs in
# the logged-in user's GUI session (so the Chromium kiosk can draw). Run with sudo
# from an unpacked package dir:  sudo bash install-macos.sh
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
VAR="/usr/local/var/kraken-player"
# Binary under the user-owned var dir (NOT /usr/local/bin, which is root-owned) so
# the non-root LaunchAgent can rename it in place on self-update - mirrors the
# Linux $DATA_DIR/bin layout. The plist ProgramArguments points here.
BIN_DIR="$VAR/bin"
BIN="$BIN_DIR/kraken-player"
HOTKEY_BIN="$BIN_DIR/whitecore-hotkeys"
PLIST="/Library/LaunchAgents/com.whitecore.kraken-player.plist"

if [[ $EUID -ne 0 ]]; then
  echo "Run with sudo: sudo $0" >&2
  exit 1
fi

# The GUI user who will actually run the kiosk (self-update + launchctl + tree
# ownership need this, not root). Pass it explicitly as $1 when the autologin/kiosk
# account differs from whoever runs the installer - it MUST match the account
# appliance-macos.sh autologs in as, or the LaunchAgent can't self-update or log.
# Falls back to the sudo user, then the console user.
GUI_USER="${1:-${SUDO_USER:-$(stat -f%Su /dev/console 2>/dev/null || echo root)}}"

mkdir -p "$BIN_DIR" "$VAR/cache"
install -m 0755 "$HERE/kraken-player" "$BIN"

# Native global shortcuts shared with Windows/Linux/Pi. Building this tiny
# helper on the target Mac avoids shipping an unsigned architecture-specific
# second binary; swiftc comes with the same Xcode Command Line Tools used by
# codesign below. RegisterEventHotKey does not require Input Monitoring access.
if [[ -f "$HERE/macos-hotkeys.swift" ]] && command -v swiftc >/dev/null 2>&1; then
  if swiftc -O "$HERE/macos-hotkeys.swift" -o "$HOTKEY_BIN"; then
    chmod 0755 "$HOTKEY_BIN"
    codesign --force --sign - "$HOTKEY_BIN" >/dev/null 2>&1 || true
    echo "Installed universal kiosk shortcuts: Ctrl+Shift+Q / Ctrl+Shift+K"
  else
    echo "  (macOS hotkey helper did not compile; install Xcode Command Line Tools and re-run)"
  fi
else
  echo "  (swiftc unavailable; install Xcode Command Line Tools for global kiosk shortcuts)"
fi

# CODE SIGNING: the binary is cross-compiled on Linux CI with no signature, and
# Apple Silicon SIGKILLs an unsigned Mach-O at exec ("killed: 9") - so without this
# the player never starts on an M-series Mac. An AD-HOC signature (sign identity
# "-") is free, needs no Apple account, and makes it executable. It does NOT satisfy
# notarization, so Gatekeeper may still prompt on first launch (right-click > Open,
# or the xattr line below). codesign ships with the Xcode Command Line Tools.
if command -v codesign >/dev/null 2>&1; then
  codesign --force --sign - "$BIN" >/dev/null 2>&1 || echo "  (ad-hoc codesign failed - if the player won't start, run: codesign --force -s - '$BIN')"
else
  echo "  (codesign not found - install Xcode CLT: xcode-select --install, then re-run)"
fi
# Clear the download-quarantine flag so Gatekeeper doesn't block the first launch.
xattr -dr com.apple.quarantine "$BIN" >/dev/null 2>&1 || true

# Bundle the ONNX Vision AI detector next to the binary (detect_onnx.py + model),
# same as Linux/Windows.
if [[ -d "$HERE/vision" ]]; then
  rm -rf "$BIN_DIR/vision"
  cp -r "$HERE/vision" "$BIN_DIR/vision"
fi

# Seed config only if absent, never clobber an already-paired device.
if [[ ! -f "$VAR/config.json" && -f "$HERE/config.json" ]]; then
  cp "$HERE/config.json" "$VAR/config.json"
fi

# ffmpeg powers CAMERA_SNAPSHOT (Vision AI). Best-effort via Homebrew (which must
# run as the non-root invoking user); the player degrades gracefully if absent.
if ! command -v ffmpeg >/dev/null 2>&1; then
  # `command` is a shell builtin, so `sudo -u USER command -v brew` tries to exec a
  # program named "command" and always fails. Run it in the user's LOGIN shell,
  # which also puts /opt/homebrew/bin (Apple Silicon) or /usr/local/bin on PATH.
  if [[ "$GUI_USER" != "root" ]] && sudo -u "$GUI_USER" -H bash -lc 'command -v brew' >/dev/null 2>&1; then
    sudo -u "$GUI_USER" -H bash -lc 'brew install ffmpeg' >/dev/null 2>&1 || echo "  (brew ffmpeg install failed - camera snapshots disabled until ffmpeg is installed)"
  else
    echo "  (ffmpeg not found - install for camera snapshots: brew install ffmpeg)"
  fi
fi

# On-device people counting runs the ONNX detector from a venv (onnxruntime, no
# torch), same as Linux. macOS ships python3 with the Xcode CLT. Best-effort.
VISION_DIR="$BIN_DIR/vision"
if [[ -f "$VISION_DIR/requirements.txt" ]] && command -v python3 >/dev/null 2>&1; then
  echo "Setting up the Vision AI detector (onnxruntime venv)..."
  python3 -m venv "$VISION_DIR/venv" >/dev/null 2>&1 || true
  if [[ -x "$VISION_DIR/venv/bin/pip" ]]; then
    "$VISION_DIR/venv/bin/pip" install --quiet --upgrade pip >/dev/null 2>&1 || true
    "$VISION_DIR/venv/bin/pip" install --quiet -r "$VISION_DIR/requirements.txt" >/dev/null 2>&1 \
      || echo "  (detector deps failed - Vision AI counting stays off until they install)"
    "$VISION_DIR/venv/bin/pip" install --quiet insightface >/dev/null 2>&1 || true
  fi
fi

# The GUI user owns the whole tree so the LaunchAgent (running as that user) can
# self-update the binary and write cache/logs.
if [[ "$GUI_USER" != "root" ]]; then
  chown -R "$GUI_USER" "$VAR" 2>/dev/null || true
fi

install -m 0644 "$HERE/com.whitecore.kraken-player.plist" "$PLIST"
chown root:wheel "$PLIST"

echo "Installed: $BIN + LaunchAgent $PLIST"

# Load it now so the operator doesn't have to run launchctl by hand. Needs the GUI
# user's Aqua session; best-effort (a headless/SSH install will load it at next login).
GUI_UID="$(id -u "$GUI_USER" 2>/dev/null || echo 0)"
if [[ "$GUI_UID" != "0" ]]; then
  launchctl bootout "gui/$GUI_UID" "$PLIST" >/dev/null 2>&1 || true
  if launchctl bootstrap "gui/$GUI_UID" "$PLIST" >/dev/null 2>&1; then
    echo "Loaded into $GUI_USER's session (it is running now)."
  else
    echo "Could not load it now (no active GUI session?). It starts at $GUI_USER's next login,"
    echo "or load it manually:  launchctl bootstrap gui/$GUI_UID \"$PLIST\""
  fi
fi

echo
echo "For an unattended kiosk (autologin + no sleep/screensaver), run:"
echo "    sudo bash appliance-macos.sh $GUI_USER"
