#!/usr/bin/env bash
# scripts/opnsense-build-config-iso.sh <config.xml path> <output.iso path>
#
# Builds a plain ISO9660 image containing /conf/config.xml, for OPNsense's
# Configuration Importer (see opentofu/README.md's "OPNsense deployment
# research" section) -- ISO9660 support was added to the Importer
# specifically so a config ISO could be attached as a secondary CD-ROM,
# mechanically identical to how modules/cloudinit-vm attaches its NoCloud
# seed via a libvirt_volume + create.content.url pointing at a local path.
#
# NOTE (updated after a 2026-07-09 audit pass): the genisoimage/xorriso flags
# below (-V volume label, -J Joliet, -R Rock Ridge) are CONFIRMED standard,
# correct usage for building a plain cross-platform ISO9660 image from a
# directory -- this part is no longer a guess. What remains genuinely
# unverified is a DIFFERENT claim: whether OPNsense's Configuration Importer
# actually reads /conf/config.xml back off an ISO9660 volume built this way
# once booted for real (neither genisoimage/xorriso nor a real OPNsense VM
# was available this session to test that end-to-end). Confirm that
# specifically before relying on it operationally.
#
# Requires: genisoimage or xorriso. Read-only w.r.t. the repo; writes only
# to <output.iso path> and a self-cleaning temp dir.
# Exit: 0 built | 1 bad input | 2 required tool missing.
set -euo pipefail

CONFIG_XML="${1:?usage: opnsense-build-config-iso.sh <config.xml> <output.iso>}"
OUT="${2:?usage: opnsense-build-config-iso.sh <config.xml> <output.iso>}"

[ -r "$CONFIG_XML" ] || { echo "FAIL: cannot read $CONFIG_XML"; exit 1; }

TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
mkdir -p "$TMP/conf"
cp "$CONFIG_XML" "$TMP/conf/config.xml"

if command -v genisoimage >/dev/null 2>&1; then
  genisoimage -o "$OUT" -V "OPNSENSE_CFG" -J -R "$TMP"
elif command -v xorriso >/dev/null 2>&1; then
  xorriso -as genisoimage -o "$OUT" -V "OPNSENSE_CFG" -J -R "$TMP"
else
  echo "FAIL: genisoimage or xorriso required on PATH"
  exit 2
fi

echo "PASS: built $OUT (contains /conf/config.xml)"
