#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${1:-$ROOT/k8s/regional/regions.env}"
OUT="${2:-$ROOT/k8s/regional/rendered}"
[[ -f "$ENV_FILE" ]] || { echo "Missing $ENV_FILE (copy regions.env.example)" >&2; exit 2; }
set -a; source "$ENV_FILE"; set +a
command -v envsubst >/dev/null || { echo "envsubst is required (gettext package)" >&2; exit 2; }
rm -rf "$OUT"; mkdir -p "$OUT"
render_region() {
  local prefix="$1"
  export REGION_ID REGION_REPLICAS XAI_UPSTREAM_URL XAI_SECRET_NAME
  REGION_ID="$(eval echo \"\${${prefix}_REGION_ID}\")"
  REGION_REPLICAS="$(eval echo \"\${${prefix}_REGION_REPLICAS}\")"
  XAI_UPSTREAM_URL="$(eval echo \"\${${prefix}_XAI_UPSTREAM_URL}\")"
  XAI_SECRET_NAME="$(eval echo \"\${${prefix}_XAI_SECRET_NAME}\")"
  envsubst < "$ROOT/k8s/regional/deployment-region.yaml" > "$OUT/deployment-${REGION_ID}.yaml"
  envsubst < "$ROOT/k8s/regional/hpa-region.yaml" > "$OUT/hpa-${REGION_ID}.yaml"
}
render_region ORD
render_region IAD
envsubst < "$ROOT/k8s/regional/service.yaml" > "$OUT/service.yaml"
envsubst < "$ROOT/k8s/regional/pdb.yaml" > "$OUT/pdb.yaml"
echo "Rendered manifests in $OUT"
