#!/bin/bash
if [ "$(id -u)" -ne 0 ]; then
	echo "switching from $(id -un) to root"
	exec sudo "$0" "$@"
fi
set -e
cd "$(dirname "$0")"
dir=$(dirname "$0")
echo "${dir}"
if mountpoint -q "$dir/mnt/efi"; then
  umount "$dir/mnt/efi"
fi
if mountpoint -q "$dir/mnt/sys"; then
  umount "$dir/mnt/sys"
fi
disk="boot_image.img"
mnt="/mnt"
efi_part="1"
root_part="2"
dd if=/dev/zero of=boot_image.img count=6000 bs=1M
parted -s "$disk" mklabel gpt 
parted -s --align=optimal "$disk" mkpart ESP fat32 1MiB 50Mib
parted -s "$disk" set "$efi_part" esp on
parted -s --align=optimal "$disk" mkpart ext4 100MiB 100%
parted -s "$disk" set "$root_part" boot on
parted -s "$disk" print
kpartx -d "$disk"
kpartx -avs "$disk"

loop="$(kpartx -l boot_image.img | grep -ow 'loop[0-9]*' | head -n 1)"
disk_efi="${loop}p1"
disk_sys="${loop}p2"

mkfs.fat -F32 -n EFI /dev/mapper/${disk_efi}
mkfs.ext4 -L ROOT /dev/mapper/${disk_sys}
rm -rf $dir/mnt/
mkdir -p $dir/mnt/
mkdir -p $dir/mnt/{efi,sys,grub}
mount -t vfat /dev/mapper/${disk_efi} $dir/mnt/efi
mount -t ext4 /dev/mapper/${disk_sys} $dir/mnt/sys
echo 'copying filesystem to mounted image'
tar -xvf ./patronagefs.tar --directory $dir/mnt/sys/
echo 'copied...'
echo "${loop}"
echo "${disk_efi}"
echo "${disk_sys}"

#--grub-mkdevicemap=$dir/mnt/device.map
#echo "(hd0) /dev/${disk_grub}" > $dir/mnt/device.map
#--efi-directory=$dir/mnt/efi --boot-directory=$dir/mnt/grub --root-directory=$dir/mnt/sys  
grub-install --target=x86_64-efi --recheck --no-floppy --efi-directory=$dir/mnt/efi --boot-directory=$dir/mnt/efi --root-directory=$dir/mnt/sys --bootloader-id=patronage /dev/$loop
#umount $dir/mnt/image
#lsblk -f
mkdir -p $dir/mnt/efi/boot/
cp $dir/initramfs.cpio.gz $dir/mnt/efi/
mkdir -p $dir/mnt/efi/EFI/patronage/
cp $dir/linux/arch/x86_64/boot/bzImage $dir/mnt/efi/EFI/patronage/bzImage
cp $dir/initramfs.cpio.gz $dir/mnt/efi/EFI/patronage/
#cp $dir/linux/arch/x86/boot/compressed/vmlinux $dir/mnt/efi/
#cp $dir/linux/arch/x86/boot/vmlinux.bin $dir/mnt/efi/
#cp $dir/initramfs.cpio.gz $dir/mnt/sys/
#cp $dir/linux/arch/x86_64/boot/bzImage $dir/mnt/sys/
#cp $dir/linux/arch/x86/boot/compressed/vmlinux $dir/mnt/sys/
#cp $dir/linux/arch/x86/boot/vmlinux.bin $dir/mnt/sys/

cp $dir/grub.cfg $dir/mnt/efi/EFI/patronage/
#cp $dir/grub.cfg $dir/mnt/sys/boot/grub/
cp $dir/grub.cfg $dir/mnt/efi/EFI/BOOT/




sync
#exit
if mountpoint -q "$dir/mnt/efi"; then
  umount "$dir/mnt/efi"
fi
if mountpoint -q "$dir/mnt/sys"; then
  umount "$dir/mnt/sys"
fi
kpartx -d boot_image.img
