#!/bin/bash
if [ "$(id -u)" -ne 0 ]; then
	echo "switching from $(id -un) to root"
	exec sudo ionice -c 3 "$0" "$@"
fi
set -e
cd "$(dirname "$0")"
cd ..
echo "$PWD"
sync
if mountpoint -q "./outputs/efi"; then
  umount "./outputs/efi"
fi
if mountpoint -q "./outputs/sys"; then
  umount "./outputs/sys"
fi
echo 'creating image..'
disk="./outputs/boot_image.img"
efi_part="1"
root_part="2"
dd if=/dev/zero of="$disk" count=12000 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"
echo 'mounting image as loopback device..'
loop="$(kpartx -l $disk | grep -ow 'loop[0-9]*' | head -n 1)"
disk_efi="${loop}p1"
disk_sys="${loop}p2"
echo 'formatting image partitions..'
mkfs.fat -F32 -n EFI /dev/mapper/${disk_efi}
mkfs.ext4 -L ROOT /dev/mapper/${disk_sys}
echo 'creating mount points..'
rm -rf ./outputs/{efi,sys,grub}
mkdir -p ./outputs/
mkdir -p ./outputs/{efi,sys,grub}
echo 'mounting loopback devices..'
mount -t vfat /dev/mapper/${disk_efi} ./outputs/efi
mount -t ext4 /dev/mapper/${disk_sys} ./outputs/sys
echo 'installing grub..'
echo "loop dev: ${loop}"
echo "efi loop: ${disk_efi}"
echo "sys loop: ${disk_sys}"
grub-install -s --compress=gz --target=x86_64-efi --recheck --no-floppy --efi-directory=./outputs/efi --boot-directory=./outputs/efi --root-directory=./outputs/sys --bootloader-id=patronage /dev/$loop
echo 'copying filesystem to mounted image..'
if mountpoint -q "./outputs/chroot/proc/"; then
  umount -lf "./outputs/chroot/proc/"
fi
cp ./config/interfaces.network ./outputs/chroot/etc/systemd/network/10-all.network
cp ./config/resolved.conf ./outputs/chroot/etc/systemd/resolved.conf
rsync -a './outputs/chroot/' './outputs/sys/'


#tar -xf ./patronagefs.tar --directory ./mnt/sys/
echo 'copied..'
echo 'copying boot files..'
mkdir -p ./outputs/efi/boot/
cp ./outputs/initramfs.cpio.gz ./outputs/efi/
mkdir -p ./outputs/efi/EFI/patronage/
cp ./outputs/bzImage ./outputs/efi/EFI/patronage/bzImage
cp ./outputs/initramfs.cpio.gz ./outputs/efi/EFI/patronage/

cp ./config/grub.cfg ./outputs/efi/EFI/patronage/
#cp $dir/grub.cfg $dir/mnt/sys/boot/grub/
cp ./config/grub.cfg ./outputs/efi/EFI/BOOT/
echo 'unmounting..'

if mountpoint -q "./outputs/efi"; then
  sync
  #fuser -kmv "$dir/mnt/efi"
  umount -lf "./outputs/efi"
fi

if mountpoint -q "./outputs/sys"; then
  sync
  #fuser -kmv "$dir/mnt/sys"
  umount -lf "./outputs/sys"
fi

kpartx -d "$disk"
chmod 777 "$disk"
echo 'image built..'
