#!/usr/bin/env bash
# REFERENCE / OPTIONAL — the normal flow uses the official Arch ISO + `git clone`
# (see README). Kept in case a self-contained custom ISO is ever wanted.
#
# Build the thin custom Arch ISO by extending the official `releng` profile with:
#   - a few explicit installer packages (extra-packages.x86_64)
#   - this repo baked into /root/arch-system-hyprland
#   - a login MOTD with install instructions (airootfs/etc/motd)
#
# Run on a machine with the `archiso` package installed (needs root for mkarchiso):
#   sudo ./run.sh [output_dir]
set -euo pipefail
cd "$(dirname "$0")"
REPO_ROOT="$(cd .. && pwd)"
OUTDIR="${1:-$REPO_ROOT/out}"
RELENG=/usr/share/archiso/configs/releng

command -v mkarchiso >/dev/null || { echo "install archiso first: pacman -S archiso"; exit 1; }
[ -d "$RELENG" ] || { echo "releng profile missing at $RELENG"; exit 1; }

WORK="$(mktemp -d)"; PROFILE="$WORK/profile"
trap 'rm -rf "$WORK"' EXIT

cp -r "$RELENG" "$PROFILE"

# extra installer packages
cat extra-packages.x86_64 >> "$PROFILE/packages.x86_64"

# our airootfs overlay (motd, etc.)
cp -aT airootfs "$PROFILE/airootfs"

# bake the repo into the live root (without git history / build output)
dest="$PROFILE/airootfs/root/arch-system-hyprland"
mkdir -p "$dest"
cp -a "$REPO_ROOT/." "$dest/"
rm -rf "$dest/.git" "$dest/out"

# mkarchiso copies airootfs with --no-preserve=mode, so exec bits are dropped and
# must be declared in profiledef's file_permissions array (the same way releng's
# own scripts get +x). We only need the bootstrap executable here; run.sh then
# restores +x across the rest of the repo at runtime, which propagates to the
# installed system. file_permissions+=(...) appends to the array defined in releng.
printf '\nfile_permissions+=(["/root/arch-system-hyprland/01-install/run.sh"]="0:0:755")\n' \
  >> "$PROFILE/profiledef.sh"

mkdir -p "$OUTDIR"
mkarchiso -v -w "$WORK/work" -o "$OUTDIR" "$PROFILE"
echo "ISO written to $OUTDIR"
