#!/usr/bin/env bash
# Installeer Web Builder API op Hermes VM107 (10.4.7.27)
set -euo pipefail

HERMES="${HERMES_SSH:-root@10.4.7.27}"
PASS="${HERMES_SSH_PASS:-Foodlinkk#2026}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=== Hermes Web Builder API → $HERMES ==="

sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "$HERMES" 'mkdir -p /opt/webbuilder-api'

sshpass -p "$PASS" scp -o StrictHostKeyChecking=no \
  "$SCRIPT_DIR/hermes-webbuilder-api.py" \
  "$HERMES:/opt/webbuilder-api/main.py"

sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "$HERMES" bash -s <<'REMOTE'
set -euo pipefail
mkdir -p /opt/webbuilder-api
python3 -m pip install -q fastapi uvicorn 2>/dev/null || pip3 install -q fastapi uvicorn

cat > /etc/systemd/system/webbuilder-api.service <<'UNIT'
[Unit]
Description=Hermes Web Builder API (agy builds)
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/webbuilder-api
Environment=PORT=8798
Environment=WEBBUILDER_PROJECTS=/home/hermes/projects
Environment=WEBBUILDER_PREVIEW_HOST=10.4.7.27
Environment=WEBBUILDER_PREVIEW_PORT=8080
ExecStart=/usr/bin/python3 /opt/webbuilder-api/main.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable webbuilder-api
systemctl restart webbuilder-api
sleep 2
curl -sf http://127.0.0.1:8798/health && echo " webbuilder-api OK"
REMOTE

echo "=== Klaar: http://10.4.7.27:8798/health ==="
