#!/usr/bin/env bash
# Install from USB/release folder on Ubuntu/Debian (linux-x64 payload).
set -euo pipefail

BUNDLE_ROOT="${1:-$(cd "$(dirname "$0")" && pwd)}"
if [[ "${EUID:-$(id -u)}" -eq 0 ]]; then
  LOG_FILE="/var/log/siraya-printer-install.log"
else
  LOG_FILE="${TMPDIR:-/tmp}/siraya-printer-install.log"
fi
INSTALL_DIR="/opt/siraya/printer"
DATA_DIR="/var/lib/siraya/printer"
HEALTH_URL="http://127.0.0.1:5000/health"

log() {
  echo "[$(date -Iseconds)] $*"
  echo "[$(date -Iseconds)] $*" >>"$LOG_FILE" 2>/dev/null || true
}

require_root() {
  if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
    echo "Re-run with sudo: sudo $0"
    exit 1
  fi
}

ensure_apt_deps() {
  if ! command -v apt-get >/dev/null 2>&1; then
    log "WARN: apt-get not found — install cups and curl manually (Ubuntu/Debian recommended)"
    return 0
  fi
  if command -v lpstat >/dev/null 2>&1 && command -v curl >/dev/null 2>&1; then
    log "System packages already present (cups, curl) — skipping apt"
    return 0
  fi
  if [[ "${SIRAYA_SKIP_APT:-}" == "1" ]]; then
    log "Skipping apt (SIRAYA_SKIP_APT=1)"
    return 0
  fi
  log "Installing system packages (cups, cups-client, curl)…"
  export DEBIAN_FRONTEND=noninteractive
  if ! apt-get install -y -qq cups cups-client curl; then
    log "WARN: apt install failed or timed out — continuing if cups/curl already exist"
  fi
  systemctl enable cups >/dev/null 2>&1 || true
  systemctl start cups >/dev/null 2>&1 || true
}

resolve_payload_dir() {
  local root="$1"
  local candidate
  for candidate in \
    "$root/payload/linux-x64" \
    "$root/service/payload/linux-x64"; do
    if [[ -f "$candidate/app/index.js" ]]; then
      echo "$candidate"
      return 0
    fi
  done
  return 1
}

warn_if_no_cups_queues() {
  if ! command -v lpstat >/dev/null 2>&1; then
    return 0
  fi
  if ! lpstat -a 2>/dev/null | grep -q .; then
    log "WARN: No CUPS printers found. Add your USB printer at http://localhost:631"
    if command -v xdg-open >/dev/null 2>&1 && [[ -n "${SUDO_USER:-}" ]]; then
      sudo -u "${SUDO_USER}" xdg-open "http://localhost:631" 2>/dev/null || true
    fi
  fi
}

wait_for_health() {
  local deadline=$((SECONDS + 60))
  log "Waiting for $HEALTH_URL"
  while (( SECONDS < deadline )); do
    if curl -fsS "$HEALTH_URL" >/dev/null 2>&1; then
      log "Health check OK"
      return 0
    fi
    sleep 2
  done
  return 1
}

open_ui() {
  if command -v xdg-open >/dev/null 2>&1; then
    sudo -u "${SUDO_USER:-$USER}" xdg-open "http://127.0.0.1:5000" 2>/dev/null || true
  else
    log "Open http://127.0.0.1:5000 in your browser"
  fi
}

install_desktop_shortcut() {
  local root="$1"
  local shortcut_script="$root/create-desktop-shortcut.sh"
  local target=""

  if [[ ! -f "$shortcut_script" && -f "$(dirname "$0")/create-desktop-shortcut.sh" ]]; then
    shortcut_script="$(dirname "$0")/create-desktop-shortcut.sh"
  fi

  for candidate in "$root"/SirayaPrinter*.AppImage; do
    if [[ -f "$candidate" ]]; then
      target="$candidate"
      break
    fi
  done
  if [[ -z "$target" && -x "$root/linux-unpacked/siraya-printer-desktop" ]]; then
    target="$root/linux-unpacked/siraya-printer-desktop"
  fi
  if [[ -z "$target" || ! -f "$shortcut_script" ]]; then
    return 0
  fi

  log "Creating desktop shortcuts"
  if [[ -n "${SUDO_USER:-}" && "$SUDO_USER" != "root" ]]; then
    sudo -u "$SUDO_USER" bash "$shortcut_script" "$target" || true
  else
    bash "$shortcut_script" "$target" || true
  fi
}

main() {
  require_root
  BUNDLE_ROOT="$(cd "$BUNDLE_ROOT" && pwd)"
  log "Bundle root: $BUNDLE_ROOT"

  ensure_apt_deps

  PAYLOAD="$(resolve_payload_dir "$BUNDLE_ROOT")" || {
    echo "Payload missing under $BUNDLE_ROOT"
    echo "Expected: service/payload/linux-x64/app/index.js (agent-linux folder)"
    echo "     or: payload/linux-x64/app/index.js (release folder)"
    exit 1
  }
  APP_SRC="$PAYLOAD/app"
  NODE_SRC="$PAYLOAD/runtime/node"

  if [[ ! -x "$NODE_SRC" ]]; then
    echo "Bundled Node missing at $NODE_SRC"
    exit 1
  fi

  log "Installing to $INSTALL_DIR"
  rm -rf "$INSTALL_DIR"
  mkdir -p "$INSTALL_DIR/runtime"
  cp -a "$APP_SRC/." "$INSTALL_DIR/"
  cp "$NODE_SRC" "$INSTALL_DIR/runtime/node"
  chmod +x "$INSTALL_DIR/runtime/node"

  export SIRAYA_INNO_INSTALL=1
  export SIRAYA_INSTALL_DIR="$INSTALL_DIR"
  export SIRAYA_DATA_DIR="$DATA_DIR"
  export SIRAYA_NODE_EXE="$INSTALL_DIR/runtime/node"

  log "Registering systemd service..."
  "$INSTALL_DIR/runtime/node" "$INSTALL_DIR/installer/linux/install-service.js"

  if ! wait_for_health; then
    echo "Service did not respond on $HEALTH_URL — check: journalctl -u siraya-printer -n 50"
    exit 1
  fi

  warn_if_no_cups_queues
  install_desktop_shortcut "$BUNDLE_ROOT"
  open_ui
  log "Installation succeeded"
}

main "$@"
