#!/bin/bash

set -e

VERDE="\033[0;32m"
AMARILLO="\033[1;33m"
ROJO="\033[0;31m"
RESET="\033[0m"

ok()   { echo -e "${VERDE}[OK]${RESET} $1"; }
info() { echo -e "${AMARILLO}[..]${RESET} $1"; }
err()  { echo -e "${ROJO}[ERROR]${RESET} $1"; exit 1; }

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OS="$(uname -s)"

echo ""
echo "============================================"
echo "  INSTALADOR SERVIDOR DE IMPRESION"
echo "  $([ "$OS" = "Darwin" ] && echo macOS || echo Linux)"
echo "============================================"
echo ""

# ── 1. Node.js ──────────────────────────────────
if ! command -v node &>/dev/null; then
  info "Node.js no encontrado. Instalando..."

  if [ "$OS" = "Darwin" ]; then
    if command -v brew &>/dev/null; then
      brew install node
    else
      err "Instala Homebrew primero: https://brew.sh  o instala Node.js desde https://nodejs.org"
    fi

  elif command -v apt-get &>/dev/null; then
    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
    sudo apt-get install -y nodejs

  elif command -v dnf &>/dev/null; then
    curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
    sudo dnf install -y nodejs

  elif command -v yum &>/dev/null; then
    curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
    sudo yum install -y nodejs

  else
    err "No se pudo instalar Node.js automáticamente. Instálalo desde https://nodejs.org"
  fi
fi

ok "Node.js $(node --version)"

# ── 2. Dependencias npm ──────────────────────────
info "Instalando dependencias..."
cd "$DIR"
npm install --omit=dev --silent
ok "Dependencias instaladas"

# ── 3. Servicio de arranque automático ──────────
if [ "$OS" = "Darwin" ]; then
  # macOS: LaunchAgent (arranca con sesión del usuario)
  PLIST="$HOME/Library/LaunchAgents/com.resto.printserver.plist"
  NODE_BIN="$(which node)"

  cat > "$PLIST" <<EOF
<?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>com.resto.printserver</string>
  <key>ProgramArguments</key>
  <array>
    <string>${NODE_BIN}</string>
    <string>${DIR}/server.js</string>
  </array>
  <key>WorkingDirectory</key>
  <string>${DIR}</string>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${DIR}/print-server.log</string>
  <key>StandardErrorPath</key>
  <string>${DIR}/print-server.log</string>
</dict>
</plist>
EOF

  launchctl unload "$PLIST" 2>/dev/null || true
  launchctl load "$PLIST"
  ok "Servicio registrado en macOS (LaunchAgent)"

else
  # Linux: systemd
  if ! command -v systemctl &>/dev/null; then
    info "systemd no disponible. El servidor no se registrará como servicio automático."
    info "Para iniciarlo manualmente: node ${DIR}/server.js"
  else
    NODE_BIN="$(which node)"
    SERVICE_FILE="/etc/systemd/system/print-server-resto.service"

    sudo tee "$SERVICE_FILE" > /dev/null <<EOF
[Unit]
Description=Servidor de impresion termica restaurante
After=network.target

[Service]
Type=simple
User=$USER
WorkingDirectory=${DIR}
ExecStart=${NODE_BIN} ${DIR}/server.js
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    sudo systemctl enable print-server-resto
    sudo systemctl restart print-server-resto
    ok "Servicio systemd registrado y activo"
  fi
fi

# ── 4. Permisos USB en Linux ─────────────────────
if [ "$OS" != "Darwin" ]; then
  if groups "$USER" | grep -qv "lp"; then
    info "Agregando usuario al grupo 'lp' para acceso a impresoras USB..."
    sudo usermod -aG lp "$USER"
    info "Deberás cerrar sesión y volver a entrar para que tome efecto el acceso USB."
  fi
fi

# ── 5. Verificar que levantó ─────────────────────
sleep 2
if curl -s http://localhost:3000/estado &>/dev/null; then
  ok "Servidor corriendo en http://localhost:3000"
else
  info "El servidor puede tardar unos segundos en iniciar."
  info "Verifica en: http://localhost:3000/estado"
fi

echo ""
echo "============================================"
echo "  INSTALACION COMPLETADA"
echo "============================================"
echo ""
echo "  Estado:   http://localhost:3000/estado"
echo "  Config:   ${DIR}/config.json"
echo "  Log:      ${DIR}/print-server.log"
echo ""
echo "  Edita config.json con las IPs de tus"
echo "  impresoras antes de usar el sistema."
echo ""
