#!/bin/bash
# btrfs-arch-mount.sh - Mount Btrfs subvolumes + boot partition for arch-chroot
# Usage: https://workspace.merith.xyz/setup-mnt.sh | bash -s -- /dev/sdX1 /dev/sdX2
#   arg1: boot partition (e.g., /dev/sda1)
#   arg2: btrfs root partition (e.g., /dev/sda2, contains @, @home, etc.)

set -euo pipefail

# Help
if [ "$#" -ne 2 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    echo "Usage: $0 <boot_partition> <btrfs_root_partition>"
    echo "Example: $0 /dev/sda1 /dev/sda2"
    exit 1
fi

BOOT_PART="$1"
ROOT_PART="$2"
MOUNT_OPTS="noatime,compress=zstd:1"

# Check root
if [ "$EUID" -ne 0 ]; then
    echo "Please run as root (sudo)." >&2
    exit 1
fi

# Check that partitions exist
if [ ! -b "$BOOT_PART" ]; then
    echo "Error: $BOOT_PART is not a block device." >&2
    exit 1
fi
if [ ! -b "$ROOT_PART" ]; then
    echo "Error: $ROOT_PART is not a block device." >&2
    exit 1
fi

# Detect UEFI or BIOS
UEFI=false
if [ -d /sys/firmware/efi ]; then
    UEFI=true
fi

# Create mount point
mkdir -p /mnt

# Mount root subvolume (the '@' subvolume)
echo "Mounting root subvolume @ from $ROOT_PART to /mnt"
mount -t btrfs -o "subvol=/@,$MOUNT_OPTS" "$ROOT_PART" /mnt


# List of other subvolumes: "destination:subvolume"
subvols=(
    "/home:/@home"
    "/root:/@root"
    "/srv:/@srv"
    "/var/cache:/@cache"
    "/var/tmp:/@tmp"
    "/var/log:/@log"
)

for entry in "${subvols[@]}"; do
    dest="/mnt${entry%%:*}"
    subvol="${entry#*:}"
    mkdir -p "$dest"
    echo "Mounting subvol $subvol to $dest"
    mount -t btrfs -o "subvol=$subvol,$MOUNT_OPTS" "$ROOT_PART" "$dest"
done

mount -t vfat $BOOT_PART /mnt/boot

echo ""
echo "All mounts complete!"
if [ "$UEFI" = true ]; then
    echo "BOOTMODE: UEFI"
else
    echo "BOOTMODE: BIOS"
fi
echo ""
echo "You can now run: sudo arch-chroot /mnt"