#!/usr/bin/env bash
# render-pack.sh — render every pack template (pack/**/*.tmpl) by injecting
# ${BASE_DOMAIN}, then rebuild the packwiz index.
#
# Pack templates are domain-dependent build output (download URLs, skin API
# roots, …). This renderer needs ONLY ${BASE_DOMAIN} — no dnsmasq HOST_LAN_IP —
# so it can run while curating mods before the full deploy config exists.
# Both tooling/render-config.sh (deploy) and tooling/add-custom-mod.sh call it.
set -euo pipefail

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

[ -f .env ] && { set -a; . ./.env; set +a; }
: "${BASE_DOMAIN:?BASE_DOMAIN unset (set in .env)}"
command -v envsubst >/dev/null 2>&1 || { echo "missing required tool: envsubst (gettext)" >&2; exit 1; }
command -v packwiz  >/dev/null 2>&1 || { echo "missing required tool: packwiz" >&2; exit 1; }
[ -f pack/pack.toml ] || { echo "pack/pack.toml not found" >&2; exit 1; }

shopt -s globstar nullglob
tmpls=(pack/**/*.tmpl)
shopt -u globstar nullglob

for t in "${tmpls[@]}"; do
  # Substitute ONLY ${BASE_DOMAIN} so any other literal $-syntax is preserved.
  envsubst '${BASE_DOMAIN}' < "$t" > "${t%.tmpl}"
  echo "rendered ${t%.tmpl}"
done

# index.toml is gitignored build output; seed a minimal one so packwiz refresh
# (which won't bootstrap a missing index) has something to populate.
[ -f pack/index.toml ] || printf 'hash-format = "sha256"\n' > pack/index.toml
( cd pack && packwiz refresh )
echo "packwiz index refreshed (${#tmpls[@]} template(s))"
