#!/usr/bin/env bash
# Fast upgrade deploy — syncs latest source, restarts service.
# Run: sudo bash DEPLOY_NOW.sh
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
RELEASE="$ROOT/dist/release"
PAYLOAD="$RELEASE/payload/linux-x64"
INSTALL_DIR="/opt/siraya/printer"
DATA="/var/lib/siraya/printer"
PORT=5000

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

unset TMPDIR

step() { echo "→ $*"; }

runtime_ok() {
  [[ -x "$PAYLOAD/runtime/node" ]]
}

step "Checking embedded Node runtime…"
if ! runtime_ok; then
  step "Building payload (Node runtime only)…"
  bash "$ROOT/installer/linux/build-payload.sh" 3.0.0 linux-x64
fi

if ! runtime_ok; then
  echo "ERROR: Embedded Node missing at $PAYLOAD/runtime/node"
  exit 1
fi

step "Setting port to $PORT in settings…"
if [[ -f "$DATA/settings.json" ]]; then
  node -e "
    const fs=require('fs');
    const p='$DATA/settings.json';
    const s=JSON.parse(fs.readFileSync(p,'utf8'));
    s.port=$PORT;
    fs.writeFileSync(p,JSON.stringify(s,null,2));
  "
fi

step "Copying latest app source to $INSTALL_DIR…"
mkdir -p "$INSTALL_DIR"
rsync -a --delete \
  --exclude dist \
  --exclude .git \
  --exclude test \
  --exclude node_modules \
  --exclude desktop/node_modules \
  "$ROOT/" "$INSTALL_DIR/"

mkdir -p "$INSTALL_DIR/runtime"
cp "$PAYLOAD/runtime/node" "$INSTALL_DIR/runtime/node"
chmod +x "$INSTALL_DIR/runtime/node"

step "Installing production dependencies…"
(cd "$INSTALL_DIR" && npm ci --omit=dev)

step "Granting CUPS/device access to siraya-printer…"
usermod -aG lp siraya-printer 2>/dev/null || true

step "Restarting siraya-printer service…"
systemctl restart siraya-printer.service

step "Waiting for health check…"
deadline=$((SECONDS + 45))
ok=0
while (( SECONDS < deadline )); do
  if curl -fsS "http://127.0.0.1:${PORT}/health" >/dev/null 2>&1; then
    ok=1
    break
  fi
  sleep 1
done

if [[ "$ok" -ne 1 ]]; then
  echo ""
  echo "Service did not respond on port $PORT."
  echo "Check logs: journalctl -u siraya-printer -n 40 --no-pager"
  exit 1
fi

LOGO_STATUS=$(curl -s "http://127.0.0.1:${PORT}/api/branding/logo/status" 2>/dev/null || echo "{}")
COUNT=$(curl -s "http://127.0.0.1:${PORT}/printers" | node -e "
  let d=''; process.stdin.on('data',c=>d+=c);
  process.stdin.on('end',()=>{ const j=JSON.parse(d); console.log(j.length); });
")

echo ""
echo "Done."
echo "  Health:  http://127.0.0.1:${PORT}/health"
echo "  UI:      http://127.0.0.1:${PORT}/designer"
echo "  Printers detected: ${COUNT}"
echo "  Logo status: ${LOGO_STATUS}"
