#!/bin/sh
# После recreate edge-сервисов Docker выдаёт новый IP; без reload nginx шлёт на старый адрес → 502.
set -eu

WATCH_INTERVAL="${IDP_NGINX_WATCH_INTERVAL:-5}"

WATCH_HOSTS="${IDP_NGINX_WATCH_HOSTS:-api-gateway:3000/health frontend:3000/}"

log() {
  echo "[idp-nginx-watch] $*"
}

probe_url() {
  target="$1"
  host="${target%%:*}"
  rest="${target#*:}"
  port="${rest%%/*}"
  path="/${rest#*/}"
  [ "$path" = "/${rest}" ] && path="/"
  wget -qO- --timeout=3 "http://${host}:${port}${path}" 2>/dev/null | head -c 64 | grep -q .
}

wait_for_upstreams() {
  attempt=0
  while [ "$attempt" -lt 120 ]; do
    ok=1
    for target in $WATCH_HOSTS; do
      if ! probe_url "$target"; then
        ok=0
        break
      fi
    done
    if [ "$ok" -eq 1 ]; then
      log "upstream-ы доступны"
      return 0
    fi
    attempt=$((attempt + 1))
    sleep 1
  done
  log "WARN: не все upstream-ы ответили за 120с — nginx стартует без ожидания"
  return 0
}

watch_upstreams() {
  last_ips=""
  while true; do
    sleep "$WATCH_INTERVAL"
    reload=0
    current_ips=""
    for target in $WATCH_HOSTS; do
      host="${target%%:*}"
      ip="$(getent hosts "$host" 2>/dev/null | awk '{print $1}' | head -n1 || true)"
      current_ips="${current_ips}${host}=${ip};"
      if ! probe_url "$target"; then
        log "${host} недоступен — reload nginx"
        reload=1
        break
      fi
    done
    if [ "$reload" -eq 0 ] && [ -n "$last_ips" ] && [ "$current_ips" != "$last_ips" ]; then
      log "IP upstream изменился — reload nginx"
      reload=1
    fi
    if [ "$reload" -eq 1 ]; then
      nginx -s reload 2>/dev/null || true
    fi
    last_ips="$current_ips"
  done
}

wait_for_upstreams
watch_upstreams &
