#!/usr/bin/env bash
# Sync dev source to installed siraya-printer service (Linux).
set -euo pipefail

SRC="$(cd "$(dirname "$0")/.." && pwd)"
DEST="/opt/siraya/printer"
DATA="/var/lib/siraya/printer"

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

unset TMPDIR

echo "Syncing $SRC -> $DEST"
rsync -a --delete \
  --exclude node_modules \
  --exclude dist \
  --exclude .git \
  "$SRC/" "$DEST/"

# Fix port in settings if .env specifies PORT=5000
if [[ -f "$DATA/.env" ]]; then
  # shellcheck disable=SC1090
  source "$DATA/.env" 2>/dev/null || true
fi
if [[ "${PORT:-5000}" == "5000" && -f "$DATA/settings.json" ]]; then
  node -e "
    const fs=require('fs');
    const p='$DATA/settings.json';
    const s=JSON.parse(fs.readFileSync(p,'utf8'));
    if(s.port!==5000){ s.port=5000; fs.writeFileSync(p,JSON.stringify(s,null,2)); console.log('Fixed settings port -> 5000'); }
  " || true
fi

echo "Restarting siraya-printer…"
systemctl restart siraya-printer.service
sleep 2

PORT="${PORT:-5000}"
if curl -fsS "http://127.0.0.1:${PORT}/health" >/dev/null 2>&1; then
  echo "Health OK on port ${PORT}"
  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('Printers detected:', j.length);
      j.slice(0,5).forEach(p=>console.log(' -', p.name, '('+p.type+')'));
    });
  "
else
  echo "WARN: health check failed on ${PORT} — try journalctl -u siraya-printer -n 30"
  exit 1
fi
