#!/usr/bin/env bash
# scripts/prereqs/install-image-tools.sh [--check|--dry-run]
#
# Prereq installer: image tooling for the OPNsense-edge build path (dc-dc
# Stage 2/3). qemu-img (from qemu-utils) is used by scripts/opnsense-prep-image.sh.
# Debian/Ubuntu (apt). Idempotent.
#
# THE ISO9660 BUILDER IS NO LONGER NEEDED (2026-07-13). It existed for
# scripts/opnsense-build-config-iso.sh, which built a config-seed ISO for the
# OPNsense Configuration Importer -- an importer that CANNOT FIRE on a
# pre-installed nano image (D-112: it probes for a read-only root, finds a
# writable one with a factory /conf/config.xml, and exits without enumerating a
# single device). The ISO was never read by anything. That script, and the whole
# config.xml delivery path, are DELETED under D-113(a2): edge config is done over
# the REST API (scripts/opnsense-api.sh). xorriso/genisoimage are therefore no
# longer installed or checked here.
#
#   --check     report qemu-img presence; exit 0/1
#   --dry-run   print what it would do; mutate nothing
#   (no flag)   install qemu-utils (sudo)
#
# Exit: 0 ok/installed | 1 check-failed | 2 bad args | 3 unsupported OS | 4 install failed.
# ASCII + LF.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$HERE/lib-prereq.sh"
PKGS="qemu-utils"

pq_parse_mode "$@"; rc=$?
[ "$rc" = "10" ] && { echo "usage: bash scripts/prereqs/install-image-tools.sh [--check|--dry-run]"; exit 0; }
[ "$rc" = "0" ] || exit "$rc"

report() {
  local ok=0
  pq_have qemu-img && echo "OK: qemu-img present" || { echo "ABSENT: qemu-img (qemu-utils)"; ok=1; }
  # No ISO9660 builder check: the config-seed ISO path is DELETED (D-112/D-113(a2)).
  return "$ok"
}

report; st=$?
[ "$PQ_CHECK" = "1" ] && exit "$st"
[ "$st" = "0" ] && { echo "-- image/ISO tooling already satisfied --"; exit 0; }

pq_require_apt "image tools" || exit 3
pq_run "apt-get update" -- sudo apt-get update || { echo "FAIL: apt-get update" >&2; exit 4; }
# shellcheck disable=SC2086
pq_run "install: $PKGS" -- sudo apt-get install -y $PKGS || { echo "FAIL: package install" >&2; exit 4; }
[ "$PQ_DRYRUN" = "1" ] && { echo "  (dry-run: no changes made)"; exit 0; }
report >/dev/null && { echo "INSTALLED: qemu-img + ISO builder"; exit 0; }
echo "FAIL: post-install check incomplete" >&2; exit 4
