#!/bin/bash
set -e

# ---- Helper to confirm actions ----
confirm() {
    read -rp "$1 [y/N]: " yn
    case $yn in
        [Yy]*) ;;
        *) echo "Aborted."; exit 1;;
    esac
}

echo "=== Arch Linux Automatic Installer ==="

# ---- Ask for target disk ----
lsblk
read -rp "Enter target disk (e.g. /dev/sda or /dev/nvme0n1): " DISK
confirm "This will ERASE ALL DATA on $DISK. Continue?"

# ---- Detect UEFI vs BIOS ----
if [[ -d /sys/firmware/efi/efivars ]]; then
    UEFI=1
    echo "UEFI system detected."
else
    UEFI=0
    echo "BIOS (legacy) system detected."
fi

# ---- Partition the disk ----
echo "=== Partitioning $DISK ==="
parted -s "$DISK" mklabel gpt

if [[ $UEFI -eq 1 ]]; then
    # UEFI: Create EFI + root
    parted -s "$DISK" mkpart ESP fat32 1MiB 513MiB
    parted -s "$DISK" set 1 esp on
    parted -s "$DISK" mkpart primary ext4 513MiB 100%
    BOOT="${DISK}p1"
    ROOT="${DISK}p2"
else
    # BIOS: Create BIOS boot + root
    parted -s "$DISK" mkpart primary 1MiB 2MiB
    parted -s "$DISK" set 1 bios_grub on
    parted -s "$DISK" mkpart primary ext4 2MiB 100%
    BOOT=""  # BIOS doesn’t require a FAT boot partition
    ROOT="${DISK}p2"
fi

sleep 1

# ---- Format partitions ----
echo "=== Formatting partitions ==="
if [[ $UEFI -eq 1 ]]; then
    mkfs.fat -F32 "$BOOT"
fi
mkfs.ext4 "$ROOT"

# ---- Mount partitions ----
echo "=== Mounting ==="
mount "$ROOT" /mnt
mkdir -p /mnt/boot

if [[ $UEFI -eq 1 ]]; then
    mkdir -p /mnt/boot/efi
    mount "$BOOT" /mnt/boot/efi
fi

# ---- Base Install ----
echo "=== Installing base system ==="
pacstrap /mnt base linux linux-firmware grub sudo openssh networkmanager

# ---- Generate fstab ----
genfstab -U /mnt >> /mnt/etc/fstab

# ---- Configure inside chroot ----
arch-chroot /mnt /bin/bash << 'EOF'

echo "=== Setting timezone & locale ==="
read -rp "Enter timezone (e.g. Europe/London): " TZ
ln -sf /usr/share/zoneinfo/"$TZ" /etc/localtime
hwclock --systohc

# enable en_US locale
sed -i 's/#en_US.UTF-8/en_US.UTF-8/' /etc/locale.gen
locale-gen
echo "LANG=en_US.UTF-8" > /etc/locale.conf

echo "=== Set hostname ==="
read -rp "Hostname: " HOST
echo "$HOST" > /etc/hostname

echo "=== Set root password ==="
passwd

echo "=== Create user ==="
read -rp "Username: " USERNAME
useradd -m -G wheel -s /bin/bash "$USERNAME"
passwd "$USERNAME"

echo "=== Enable wheel sudo ==="
sed -i 's/# %wheel ALL=(ALL:ALL) ALL/%wheel ALL=(ALL:ALL) ALL/' /etc/sudoers

echo "=== Enable services ==="
systemctl enable sshd
systemctl enable NetworkManager

echo "=== Install GRUB ==="
if [[ -d /sys/firmware/efi/efivars ]]; then
    # UEFI mode
    pacman -Sy --noconfirm efibootmgr
    grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=GRUB
else
    # BIOS mode
    grub-install --target=i386-pc "$DISK"
fi

grub-mkconfig -o /boot/grub/grub.cfg

EOF

echo "=== Installation Complete ==="
echo "You can reboot now:   reboot"
