#!/usr/bin/env bash
# Assemble the TANINUX archiso profile = canonical `releng` base + our overrides,
# then (optionally) build the ISO. Run as your user; mkarchiso uses sudo.
#
#   sudo pacman -S archiso          # once
#   ./bootstrap-profile.sh          # assemble ./build-profile/
#   ./bootstrap-profile.sh --build  # assemble + mkarchiso -> ./out/
#
# Why this approach: we don't hand-maintain the bootloader/mkinitcpio boilerplate
# (error-prone) — we take it from the authoritative releng profile and only
# overlay our deltas (profiledef, pacman.conf, packages, airootfs, calamares).
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
RELENG=/usr/share/archiso/configs/releng
PROFILE="$HERE/build-profile"

[ -d "$RELENG" ] || { echo "archiso not installed — run: sudo pacman -S archiso"; exit 1; }

echo "==> base: copy releng -> build-profile"
rm -rf "$PROFILE"
cp -r "$RELENG" "$PROFILE"

echo "==> kernel: live ISO uses linux-zen (matches the target)"
sed -i 's/^linux$/linux-zen/' "$PROFILE/packages.x86_64"
# point the live boot entries at the zen kernel images
grep -rl -e 'vmlinuz-linux' -e 'initramfs-linux' \
  "$PROFILE/efiboot" "$PROFILE/syslinux" "$PROFILE/grub" 2>/dev/null \
  | xargs -r sed -i -e 's/vmlinuz-linux/vmlinuz-linux-zen/g' \
                    -e 's/initramfs-linux/initramfs-linux-zen/g'

echo "==> overlay TANINUX overrides"
cat "$HERE/overrides/packages.x86_64" >> "$PROFILE/packages.x86_64"
install -m644 "$HERE/overrides/profiledef.sh" "$PROFILE/profiledef.sh"
install -m644 "$HERE/overrides/pacman.conf"   "$PROFILE/pacman.conf"
cp -rT "$HERE/overrides/airootfs" "$PROFILE/airootfs"

echo "==> profile ready: $PROFILE"
if [ "${1:-}" = "--build" ]; then
  echo "==> building ISO (sudo mkarchiso) …"
  sudo mkarchiso -v -w /tmp/tanin-work -o "$HERE/out" "$PROFILE"
  echo "ISO written to $HERE/out/"
else
  echo "build with:  sudo mkarchiso -v -w /tmp/tanin-work -o \"$HERE/out\" \"$PROFILE\""
fi
