#!/usr/bin/env bash
# Re-add the ephemeral q4.suby.pl route only while the local gateway is healthy.
set -u
ADMIN="http://10.6.0.105:2019"
ROUTES="$ADMIN/config/apps/http/servers/srv1/routes"
ROUTE_JSON="/srv/q4/tools/caddy-route.json"
HOST="q4.suby.pl"

if curl -s --max-time 5 "$ROUTES" | grep -q "\"$HOST\""; then
  exit 0
fi

health=$(curl -fsS --max-time 3 http://127.0.0.1:3280/healthz) || exit 0
grep -q '"status":"ok"' <<<"$health" || exit 0
grep -q '"dedicated":true' <<<"$health" || exit 0
grep -q '"retail":true' <<<"$health" || exit 0

if curl -fsS --max-time 5 -X POST -H 'Content-Type: application/json' \
     -d @"$ROUTE_JSON" "$ROUTES" >/dev/null; then
  logger -t q4-caddy-watchdog "re-added missing $HOST route on r2d2 Caddy"
else
  logger -t q4-caddy-watchdog "FAILED to re-add $HOST route on r2d2 Caddy"
fi
