#!/usr/bin/env bash
# One-shot entry for dist/agent-linux/ — install service + launch desktop app.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
LOG_FILE="${TMPDIR:-/tmp}/siraya-printer-install.log"

log() {
  echo "[$(date -Iseconds)] $*" | tee -a "$LOG_FILE"
}

chmod +x "$ROOT/install-from-folder.sh" 2>/dev/null || true
for appimg in "$ROOT"/SirayaPrinter*.AppImage; do
  [[ -f "$appimg" ]] && chmod +x "$appimg"
done

if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
  log "Elevating with sudo…"
  exec sudo -E bash "$0" "$@"
fi

log "Siraya Printer Linux install from $ROOT"
bash "$ROOT/install-from-folder.sh" "$ROOT"

APPIMG=""
UNPACKED=""
for candidate in "$ROOT"/SirayaPrinter*.AppImage; do
  if [[ -f "$candidate" ]]; then
    APPIMG="$candidate"
    break
  fi
done
if [[ -z "$APPIMG" && -x "$ROOT/linux-unpacked/siraya-printer-desktop" ]]; then
  UNPACKED="$ROOT/linux-unpacked/siraya-printer-desktop"
fi

TARGET_USER="${SUDO_USER:-${INSTALL_USER:-}}"
DESKTOP_TARGET="${APPIMG:-$UNPACKED}"
if [[ -n "$DESKTOP_TARGET" && -f "$ROOT/create-desktop-shortcut.sh" ]]; then
  log "Creating desktop shortcuts"
  if [[ -n "$TARGET_USER" && "$TARGET_USER" != "root" ]]; then
    sudo -u "$TARGET_USER" bash "$ROOT/create-desktop-shortcut.sh" "$DESKTOP_TARGET" || true
  else
    bash "$ROOT/create-desktop-shortcut.sh" "$DESKTOP_TARGET" || true
  fi
fi

if [[ -n "$APPIMG" && -n "$TARGET_USER" && "$TARGET_USER" != "root" ]]; then
  log "Launching desktop app for $TARGET_USER"
  sudo -u "$TARGET_USER" env DISPLAY="${DISPLAY:-:0}" XAUTHORITY="${XAUTHORITY:-}" \
    "$APPIMG" >/dev/null 2>&1 &
elif [[ -n "$APPIMG" ]]; then
  log "Launching desktop app"
  env DISPLAY="${DISPLAY:-:0}" "$APPIMG" >/dev/null 2>&1 &
fi

echo ""
echo "Installation complete."
echo "  Desktop app: SirayaPrinter.AppImage"
echo "  Setup UI:    http://127.0.0.1:5000"
echo "  POS (same PC): https://pos.siraya.food/pos"
echo ""
