#!/usr/bin/env bash
# Render one nginx vhost per app from deploy/apps.conf + nginx/site.conf.template.
#
#   deploy/bin/exo-render-nginx            # writes to ./rendered/
#   deploy/bin/exo-render-nginx /etc/nginx/sites-available
set -Eeuo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUT="${1:-$HERE/rendered}"
TPL="$HERE/nginx/site.conf.template"
mkdir -p "$OUT"

while IFS='|' read -r app domain port tag; do
  [[ -z ${app:-} || $app == \#* ]] && continue
  if [[ $domain == *_DOMAIN ]]; then
    echo "SKIP $app: domain is still the placeholder '$domain' — edit deploy/apps.conf" >&2
    continue
  fi
  sed -e "s/{{APP}}/$app/g" -e "s/{{DOMAIN}}/$domain/g" -e "s/{{PORT}}/$port/g" \
    "$TPL" > "$OUT/exo-$app.conf"
  echo "wrote $OUT/exo-$app.conf  ($domain -> 127.0.0.1:$port)"
done < "$HERE/apps.conf"
