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

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

PROXY_IMAGE="${PROXY_IMAGE:-nginx:1.27-alpine}"
PROXY_CONTAINER_NAME="${PROXY_CONTAINER_NAME:-beaver-router-proxy}"
PROXY_NETWORK_NAME="${PROXY_NETWORK_NAME:-beaver-instance-edge}"
PROXY_HTTP_PORT="${PROXY_HTTP_PORT:-8088}"
REGISTRY_PATH="${REGISTRY_PATH:-${SCRIPT_DIR}/../app-instance/runtime/registry/instances.json}"
OUTPUT_PATH="${OUTPUT_PATH:-${SCRIPT_DIR}/runtime/conf.d/instances.conf}"
REPLACE=0

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

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

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

if ! docker network inspect "$PROXY_NETWORK_NAME" >/dev/null 2>&1; then
  docker network create "$PROXY_NETWORK_NAME" >/dev/null
fi

if docker container inspect "$PROXY_CONTAINER_NAME" >/dev/null 2>&1; then
  if [[ "$REPLACE" -eq 1 ]]; then
    docker rm -f "$PROXY_CONTAINER_NAME" >/dev/null
  else
    printf '[start-proxy] container already running: %s\n' "$PROXY_CONTAINER_NAME"
    exit 0
  fi
fi

mkdir -p "${SCRIPT_DIR}/runtime/conf.d"

docker run -d \
  --name "$PROXY_CONTAINER_NAME" \
  --restart unless-stopped \
  --network "$PROXY_NETWORK_NAME" \
  -p "${PROXY_HTTP_PORT}:80" \
  -v "${SCRIPT_DIR}/nginx.conf:/etc/nginx/nginx.conf:ro" \
  -v "${SCRIPT_DIR}/runtime/conf.d:/etc/nginx/conf.d:ro" \
  "$PROXY_IMAGE" >/dev/null

printf 'container_name=%s\n' "$PROXY_CONTAINER_NAME"
printf 'network_name=%s\n' "$PROXY_NETWORK_NAME"
printf 'http_port=%s\n' "$PROXY_HTTP_PORT"
