#!/usr/bin/env bash
# Deploy the canary service to a remote host via rsync + ssh.
# Usage: ./deploy.sh [host]  (default: minerva.lan)
set -euo pipefail

HOST="${1:-minerva.lan}"
REMOTE_DIR="/opt/stacks/doctate-canary"
LOCAL_DIR="$(cd "$(dirname "$0")" && pwd)"

echo ">>> Syncing $LOCAL_DIR -> $HOST:$REMOTE_DIR"
rsync -av \
  --exclude 'deploy.sh' \
  --exclude 'models/' \
  "$LOCAL_DIR/" "$HOST:$REMOTE_DIR/"

echo ">>> Rebuilding + restarting on $HOST"
# Pre-pull the base image with the Docker engine before `docker build`.
# Docker's legacy builder hits a TLS cert error on the pull path; pulling
# first means the build finds the layer in cache and skips that step.
# Keep this tag in sync with the FROM line in the Dockerfile.
ssh "$HOST" "cd $REMOTE_DIR && \
  docker compose down && \
  docker pull nvidia/cuda:12.6.1-devel-ubuntu22.04 && \
  docker build -t doctate-canary . && \
  docker compose up -d"

echo ">>> Waiting for /health (up to 10 min for first model download + warmup)"
for i in $(seq 1 120); do
  if ssh "$HOST" "curl -sf http://localhost:9002/health" 2>/dev/null; then
    echo
    echo ">>> OK"
    ssh "$HOST" "curl -s http://localhost:9002/info"
    echo
    exit 0
  fi
  sleep 5
done

echo ">>> TIMEOUT — last logs:"
ssh "$HOST" "docker logs doctate-canary --tail 60"
exit 1
