#!/bin/sh
#
# creating uefi boot stick - delete partitions first
#
PATH=/usr/local/bin:/usr/local/sbin:/bin:/sbin

# Check root
if [ "$(id -u)" -ne 0 ]; then
    echo "Error: Must run as root"
    exit 1
fi

vmt-install grub-efi-2.12 util-linux-2.41.1


INFO=$(lsblk -o NAME,SIZE,TYPE,MODEL,RM | awk '$5 == 1')
echo "${INFO}"
read -p "Use this removable device? (y/n): " USE_DEVICE

if [ "$USE_DEVICE" = "y" ] || [ "$USE_DEVICE" = "Y" ]; then
    DISK=$(echo "$INFO" | awk '{print $1}')
    echo "Using device: /dev/${DISK}"
else
    echo "Aborted"
    exit 1
fi

DEVROOT=/dev/${DISK}
MNTROOT=/mnt/${DISK}
DEVPART=/dev/${DISK}1
MNTPART=/mnt/${DISK}1
BOOTDIR=/mnt/${DISK}1/boot

# Delete all partitions
(echo d; echo 1; echo d; echo 2; echo d; echo 3; echo d; echo 4; echo w) | fdisk ${DEVROOT} 1>/dev/null 2>/dev/null

# Create new GPT partition table and single partition
(echo g; echo n; echo 1; echo ''; echo ''; echo t; echo uefi; echo w) | fdisk ${DEVROOT} 1>/dev/null 2>/dev/null

mkfs.vfat ${DEVPART}
mkdir -p ${MNTPART}
mount -o rw ${DEVPART} ${MNTPART}
grub-install --target=x86_64-efi --removable --efi-directory=${MNTPART} --boot-directory=${BOOTDIR}
cat > ${BOOTDIR}/grub/grub.cfg << EOF
# Begin /boot/grub/grub.cfg
set default=0
set timeout=0
hiddenmenu

insmod part_gpt

menuentry "vmtux64-6.16.8 Sat Sep 20 08:09:15 CEST 2025" {
    clear
    linux /boot/vmlinuz64-6.16.8 loglevel=3 fbcon=map:0
    initrd /boot/vmtux64-2.5.gz
}
EOF

cp -v /mnt/tux/boot/vmlinuz64-* ${BOOTDIR}
cp -v /mnt/tux/boot/vmtux64-*.gz ${BOOTDIR}

umount ${MNTPART}
