#!/usr/bin/env bash
# render-nginx.sh — render an nginx vhost template with the .env values.
#
# Substitutes $BASE_DOMAIN, $APP_DIR, $CADDY_HTTP_PORT into a template and
# prints the result to stdout, or installs it with --install (writes to
# sites-available, symlinks sites-enabled, tests, reloads nginx).
#
# Usage:
#   tooling/render-nginx.sh                 # render caddy-front template -> stdout
#   tooling/render-nginx.sh --install       # render + install + reload nginx
#   TEMPLATE=nginx/ulicraft.conf.tmpl tooling/render-nginx.sh   # the static variant
#
# .env vars used:
#   BASE_DOMAIN       required
#   CADDY_HTTP_PORT   caddy-front template only (localhost port nginx proxies to)
# optional:
#   APP_DIR           host path to this repo (cert files live under APP_DIR/certs)
#                     — defaults to the repo root (this checkout)
#   TEMPLATE          template to render (default nginx/ulicraft-caddy.conf.tmpl)
#   SITE_NAME         installed filename (default ulicraft.conf)
set -euo pipefail

cd "$(dirname "$0")/.."   # repo root

log()  { printf '\n\033[1;32m==>\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m!!\033[0m %s\n' "$*" >&2; }
die()  { printf '\033[1;31mxx\033[0m %s\n' "$*" >&2; exit 1; }

[ -f .env ] || die ".env not found (copy .env.example and fill it)"
# shellcheck disable=SC1091
set -a; . ./.env; set +a
: "${BASE_DOMAIN:?BASE_DOMAIN unset in .env}"

TEMPLATE="${TEMPLATE:-nginx/ulicraft-caddy.conf.tmpl}"
[ -f "$TEMPLATE" ] || die "template not found: $TEMPLATE"
APP_DIR="${APP_DIR:-$PWD}"
SITE_NAME="${SITE_NAME:-ulicraft.conf}"

# CADDY_HTTP_PORT only matters for the caddy-front template; default 80 so the
# static template (which never references it) still renders cleanly.
export BASE_DOMAIN APP_DIR
export CADDY_HTTP_PORT="${CADDY_HTTP_PORT:-80}"

rendered="$(envsubst '$BASE_DOMAIN $APP_DIR $CADDY_HTTP_PORT' < "$TEMPLATE")"

if [ "${1:-}" != "--install" ]; then
  printf '%s\n' "$rendered"
  warn "dry run — pipe to a file or pass --install to deploy"
  exit 0
fi

command -v nginx >/dev/null 2>&1 || die "nginx not found on PATH"
avail="/etc/nginx/sites-available/$SITE_NAME"
enabled="/etc/nginx/sites-enabled/$SITE_NAME"

log "installing $TEMPLATE -> $avail (APP_DIR=$APP_DIR, CADDY_HTTP_PORT=$CADDY_HTTP_PORT)"
printf '%s\n' "$rendered" | sudo tee "$avail" >/dev/null
sudo ln -sf "$avail" "$enabled"
sudo nginx -t
sudo systemctl reload nginx
log "done — nginx reloaded"
