#!/usr/bin/env bash
# Base Arch install, run from the live ISO (as root, UEFI).
# Partitions DISK, installs a minimal base, sets up systemd-boot + mkinitcpio, then
# hands off to the system + user provisioning layers after first boot.
#
#   ./run.sh            # reads ../system.conf
set -euo pipefail
cd "$(dirname "$0")"
source ../02-system/lib.sh
source ../system.conf
REPO_ROOT="$(cd .. && pwd)"

# Safety net: if the repo arrived without exec bits (USB on exFAT, or the optional
# custom ISO which strips modes), restore +x so the copies we propagate to the
# installed system are runnable. Harmless when git already preserved them.
find "$REPO_ROOT" -name '*.sh' -exec chmod +x {} + 2>/dev/null || true

[ "$(id -u)" -eq 0 ] || die "run as root from the live ISO"
[ -d /sys/firmware/efi ] || die "not booted in UEFI mode"
[ -b "$DISK" ] || die "DISK '$DISK' is not a block device — edit system.conf"

echo "About to ERASE $DISK and install Arch (host=$HOSTNAME user=$USERNAME)."
read -rp "Type ERASE to continue: " ans
[ "$ans" = ERASE ] || die "aborted"

source ./00-partition.sh      # partitions + mounts /mnt, /mnt/boot
source ./05-mirrors.sh        # rank pacman mirrors (fast DE) before pacstrap
source ./10-pacstrap.sh       # base system + fstab + copy repo to /mnt/root

# in-chroot steps (the whole repo, incl. system.conf, was copied by 10-pacstrap)
arch-chroot /mnt bash /root/arch-system-hyprland/01-install/20-boot.sh
arch-chroot /mnt bash /root/arch-system-hyprland/01-install/30-finalize.sh

info "Base install done. Reboot, remove the ISO, then as your user run:"
info "  sudo ~/arch-system-hyprland/02-system/run.sh"
info "  ~/arch-system-hyprland/03-user/run.sh"
