#!/bin/sh

# Mostly intended to be used to create a boot device with an USB key

# Ask the device to use for EFI partition
# Create partition label and new partition if not present
# Format the partition
# Create the mountpoint and mount the partition
# Add an entry in /etc/fstab with systemd-automount
# Install efibootmgr and efivar to be able to manage EFI entries

EFI_MOUNTPATH="/boot/efi"

# Show a warning if not in a chroot (a rescue/chroot mode is mostly attempted)
if ! ischroot; then
	printf "%s" "Take care, you are not in a chroot environment !\n"
fi

# Select the future EFI partition
printf "%b" "All data on the selected device will be deleted ! Be sure to know what you are doing !\n"
printf "%b" "Select device and partition to use for UEFI Stub (eg. /dev/sdX1) :\n"
read -r EFI_PARTITION

# Test if partition exists
if [ ! -b "${EFI_PARTITION}" ]; then
	EFI_DEVICE=$(printf "%s" "${EFI_PARTITION}" | sed "s;\(/dev/...\).*;\1;")

	printf "%b\n" "${EFI_PARTITION} partition doesn't exist. Create it with parted."
	parted "${EFI_DEVICE}" mklabel gpt
	parted "${EFI_DEVICE}" mkpart primary 1049kB 1gB
fi

# Enable boot flag
parted "${EFI_DEVICE}" set 1 boot on
# Format in vfat
mkfs.fat "${EFI_PARTITION}"

# Create mountpoint if needed
mkdir -p -- "${EFI_MOUNTPATH}"
# And mount it if not already mounted
mountpoint -q "${EFI_MOUNTPATH}"   || mount -- "${EFI_PARTITION}" "${EFI_MOUNTPATH}"

# Add EFI device automount in fstab
EFI_UUID=$(blkid -s UUID -o value "${EFI_PARTITION}")
printf "%b\n" "UUID=${EFI_UUID}              ${EFI_MOUNTPATH}       vfat    defaults,x-systemd.automount,x-systemd.device-timeout=2,x-systemd.idle-timeout=1min,noatime,noauto   0  2" >> /etc/fstab

# Install required packages
aptitude install -y efibootmgr efivar

# Copy kernel and initrd
printf "%b" "${EFI_MOUNTPATH} is ready, you can copy your kernel/initrd or uefi blob.\n"

exit 0