#!/usr/bin/env bash
# Setup / update BKRY Dispatch on Ubuntu/Debian: Node 22, systemd service, nginx, free HTTPS.
# Usage:  sudo bash scripts/deploy.sh dispatch.yourbkrydomain.com it@yourbkrydomain.com
# Safe to re-run for updates: keeps .env, data/ (users) and your app's index.html.
set -euo pipefail
DOMAIN="${1:-}"; EMAIL="${2:-}"
APP_DIR=/opt/bkry-dispatch
HERE="$(cd "$(dirname "$0")/.." && pwd)"

[ "$(id -u)" = 0 ] || { echo "Run with sudo."; exit 1; }
[ -n "$DOMAIN" ] && [ -n "$EMAIL" ] || { echo "Usage: sudo bash scripts/deploy.sh dispatch.example.com it@example.com"; exit 1; }

echo "==> Packages"
apt-get update -y
apt-get install -y nginx certbot python3-certbot-nginx python3 curl ca-certificates
NODE_MAJOR=$(node -v 2>/dev/null | sed 's/v\([0-9]*\).*/\1/' || echo 0)
if [ "${NODE_MAJOR:-0}" -lt 18 ]; then
  echo "==> Installing Node.js 22"
  curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
  apt-get install -y nodejs
fi
node -v

echo "==> App files -> $APP_DIR"
id bkry >/dev/null 2>&1 || useradd --system --home "$APP_DIR" --shell /usr/sbin/nologin bkry
mkdir -p "$APP_DIR/data"
KEEP_INDEX=""
if [ -f "$APP_DIR/public/index.html" ] && ! grep -q "Placeholder — login" "$APP_DIR/public/index.html"; then
  KEEP_INDEX=$(mktemp); cp "$APP_DIR/public/index.html" "$KEEP_INDEX"
fi
if [ "$HERE" != "$APP_DIR" ]; then
  cp -r "$HERE/server.js" "$HERE/lib" "$HERE/public" "$HERE/scripts" "$HERE/deploy" "$HERE/README.md" "$HERE/.env.example" "$APP_DIR/"
fi
[ -n "$KEEP_INDEX" ] && cp "$KEEP_INDEX" "$APP_DIR/public/index.html" && echo "   (kept your existing app page)"
[ -f "$APP_DIR/.env" ] || cp "$APP_DIR/.env.example" "$APP_DIR/.env"
chown -R bkry:bkry "$APP_DIR"
chmod 700 "$APP_DIR/data"

echo "==> Service"
cp "$HERE/deploy/bkry-dispatch.service" /etc/systemd/system/bkry-dispatch.service
systemctl daemon-reload
systemctl enable bkry-dispatch
systemctl restart bkry-dispatch
sleep 1
curl -fsS http://127.0.0.1:3100/api/health && echo

echo "==> nginx for $DOMAIN"
sed "s/DOMAIN_PLACEHOLDER/$DOMAIN/g" "$HERE/deploy/nginx-bkry-dispatch.conf" > /etc/nginx/sites-available/bkry-dispatch
ln -sf /etc/nginx/sites-available/bkry-dispatch /etc/nginx/sites-enabled/bkry-dispatch
nginx -t && systemctl reload nginx
if command -v ufw >/dev/null && ufw status | grep -q active; then ufw allow 'Nginx Full'; fi

echo "==> HTTPS certificate (DNS for $DOMAIN must already point here)"
certbot --nginx -d "$DOMAIN" -m "$EMAIL" --agree-tos --redirect --non-interactive

echo
echo "Done:  https://$DOMAIN"
echo "Login:  admin / admin   (change it from the menu → Change password)"
echo "Add your app:  sudo bash $APP_DIR/scripts/add-app.sh /path/to/dispatch.html"
