#!/usr/bin/env bash
# Restart doctate-server on a remote Docker host (default: minerva.lan).
# Use after editing /opt/stacks/doctate-server/config/{users,settings}.toml
# or .env — the server reads those at boot, not per request.
#
# Usage: ./scripts/restart-server.sh [host]
#   host  default: minerva.lan
#
# Exit code 0 on healthy server, 1 on health-check timeout.

set -euo pipefail

HOST="${1:-minerva.lan}"
REMOTE="/opt/stacks/doctate-server"

echo ">>> Restarting doctate-server on $HOST"
ssh "$HOST" "docker compose -f $REMOTE/compose.yaml restart doctate-server"

echo ">>> Waiting for /api/health"
for i in $(seq 1 20); do
    if curl -fsS "http://$HOST:3000/api/health" >/dev/null 2>&1; then
        echo "    OK after ${i} attempt(s)"
        curl -s "http://$HOST:3000/api/health"
        echo
        exit 0
    fi
    sleep 2
done

echo ">>> TIMEOUT (40s) — last 50 lines of container logs:" >&2
ssh "$HOST" "docker logs --tail 50 doctate-server" >&2 || true
exit 1
