#!/usr/bin/env bash
# dms-api installer — run on the host that has the `mailserver` container.
set -euo pipefail

: "${DMS_API_TOKEN:?DMS_API_TOKEN must be exported (e.g. export DMS_API_TOKEN=\$(openssl rand -hex 24))}"
HERE="$(cd "$(dirname "$0")" && pwd)"
cd "$HERE"

log() { printf '\033[1;36m[dms-api]\033[0m %s\n' "$*"; }
die() { printf '\033[1;31m[dms-api]\033[0m %s\n' "$*" >&2; exit 1; }

command -v docker >/dev/null || die "docker CLI not found on PATH"
docker ps --format '{{.Names}}' | grep -qx mailserver || die "mailserver container not running"

log "building dms-api image"
docker build -t dms-api:latest .

log "starting dms-api"
docker compose up -d

log "waiting for /health to come up"
for i in $(seq 1 30); do
  if curl -fsS --max-time 2 http://127.0.0.1:8791/health >/dev/null 2>&1; then
    log "dms-api healthy on 127.0.0.1:8791"
    break
  fi
  sleep 1
done

log "test authenticated probe"
curl -fsS -o /dev/null -w '  auth=%{http_code}\n' \
  -H "Authorization: Bearer $DMS_API_TOKEN" \
  http://127.0.0.1:8791/health/auth || log "  (warning: auth probe failed)"

log "done. Front this with caddy/nginx + LE for HTTPS."
