#!/bin/bash
set -euo pipefail
HOST106="aissa@10.4.7.18"
HOST19="aissa@10.4.7.19"
PASS='Foodlinkk#2026'
BASE="/tmp/foodlinkk-deploy"

echo "==> Deploy cockpit label + docling UI to VM106"
sshpass -p "$PASS" rsync -az \
  "$BASE/cockpit/app/routes/admin_api.py" \
  "$BASE/cockpit/app/routes/documents.py" \
  "$BASE/cockpit/templates/documents.html" \
  "$BASE/cockpit/static/css/documents-workbench.css" \
  "$BASE/migrations/028_docling_results.sql" \
  "$HOST106:~/foodlinkk-command-center/"

sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "$HOST106" <<'REMOTE106'
cd ~/foodlinkk-command-center
docker exec -i foodlinkk_db psql -U aissa -d foodlinkk < migrations/028_docling_results.sql 2>/dev/null || true
cp -f admin_api.py cockpit/app/routes/admin_api.py
cp -f documents.py cockpit/app/routes/documents.py
cp -f documents.html cockpit/templates/documents.html
cp -f documents-workbench.css cockpit/static/css/documents-workbench.css
docker compose build cockpit && docker compose up -d cockpit
REMOTE106

echo "==> Deploy Docling to doc-ingest VM19"
sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "$HOST19" 'mkdir -p ~/foodlinkk-ai/doc-ingest/app'
sshpass -p "$PASS" scp -o StrictHostKeyChecking=no \
  "$BASE/doc-ingest/app/docling_service.py" \
  "$BASE/doc-ingest/app/docling_routes.py" \
  "$HOST19:~/foodlinkk-ai/doc-ingest/app/"

sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "$HOST19" <<'REMOTE19'
set -e
cd ~/foodlinkk-ai/doc-ingest
grep -q '^docling' requirements.txt || echo 'docling>=2.14.0' >> requirements.txt
grep -q 'docling_routes' app/main.py || python3 <<'PY'
from pathlib import Path
p = Path("app/main.py")
text = p.read_text()
if "docling_routes" not in text:
    text = text.replace(
        "from app.pptx_template import ensure_blank_template",
        "from app.pptx_template import ensure_blank_template\nfrom app.docling_routes import router as docling_router",
    )
    needle = 'app = FastAPI(title="Foodlinkk Doc Ingest"'
    pos = text.find(needle)
    if pos >= 0:
        line_end = text.find("\n", pos)
        text = text[: line_end + 1] + "\napp.include_router(docling_router)\n" + text[line_end + 1 :]
    p.write_text(text)
    print("patched main.py")
PY
if ! grep -q 'libgl1' Dockerfile; then
  sed -i 's/libpq5/libpq5 libgl1 libglib2.0-0 libgomp1/' Dockerfile
fi
docker compose up -d --build 2>&1 | tail -20
REMOTE19

echo "==> Done"
