#!/usr/bin/env bash
# Deploy the whisper 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-whisper"
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"
ssh "$HOST" "cd $REMOTE_DIR && \
  docker compose down && \
  docker build -t doctate-whisper . && \
  docker compose up -d"

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

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