#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RENDER_SCRIPT="${SCRIPT_DIR}/render-routes.py"
START_SCRIPT="${SCRIPT_DIR}/start-proxy.sh"

PROXY_CONTAINER_NAME="${PROXY_CONTAINER_NAME:-beaver-router-proxy}"
REGISTRY_PATH="${REGISTRY_PATH:-${SCRIPT_DIR}/../app-instance/runtime/registry/instances.json}"
OUTPUT_PATH="${OUTPUT_PATH:-${SCRIPT_DIR}/runtime/conf.d/instances.conf}"
START_IF_MISSING=0

usage() {
  cat <<'EOF'
Usage:
  ./reload-proxy.sh [--start-if-missing]
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --start-if-missing)
      START_IF_MISSING=1
      shift
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      printf '[reload-proxy] unknown argument: %s\n' "$1" >&2
      exit 1
      ;;
  esac
done

python3 "$RENDER_SCRIPT" --registry "$REGISTRY_PATH" --output "$OUTPUT_PATH" >/dev/null

if ! docker container inspect "$PROXY_CONTAINER_NAME" >/dev/null 2>&1; then
  if [[ "$START_IF_MISSING" -eq 1 ]]; then
    "$START_SCRIPT"
    exit 0
  fi
  printf '[reload-proxy] proxy container not found: %s\n' "$PROXY_CONTAINER_NAME" >&2
  exit 1
fi

docker exec "$PROXY_CONTAINER_NAME" nginx -t >/dev/null
docker exec "$PROXY_CONTAINER_NAME" nginx -s reload >/dev/null
printf 'container_name=%s\n' "$PROXY_CONTAINER_NAME"
