#!/bin/bash

source "/tmp/scripts.env"

DISK_PATH="/dev/${DISK}"
ROOT_PART_NUM=3

case "${DISK}" in
  nvme*)
    ROOT_PART_PATH="${DISK_PATH}p${ROOT_PART_NUM}"
  ;;
  *)
    ROOT_PART_PATH="${DISK_PATH}${ROOT_PART_NUM}"
  ;;
esac

LAST_PART_NUM="$(parted ${DISK_PATH} -ms unit s p | tail -n 1 | cut -f 1 -d:)"
if [ "${LAST_PART_NUM}" != "${ROOT_PART_NUM}" ]; then
    whiptail --msgbox "${ROOT_PART_PATH} is not the last partition (${LAST_PART_NUM}). Don't know how to expand" 20 60 2
    exit 1
fi

# Get the starting offset of the root partition
ROOT_PART_START="$(parted ${DISK_PATH} -ms unit s p | tail -n 1 | cut -f 2 -d:|cut -f 1 -ds|cut -f 2 -d:)"
[ "${ROOT_PART_START}" ] || return 1

gdisk "${DISK_PATH}" <<EOF
p
v
x
e
p
w
y
EOF

sleep 5

fdisk "${DISK_PATH}" <<EOF
p
d
${ROOT_PART_NUM}
n
${ROOT_PART_NUM}
${ROOT_PART_START}

p
w
EOF

sleep 5
partprobe "${DISK_PATH}"
sleep 5

e2fsck -f "${ROOT_PART_PATH}"
resize2fs "${ROOT_PART_PATH}"
partprobe "${DISK_PATH}"
sleep 5

mount "${ROOT_PART_PATH}" /mnt
mount -t proc proc /mnt/proc
mount -o bind /dev /mnt/dev

mkdir -p /mnt/root
cp -rvf /run/live/medium/home/partimag/$IMAGE/addons /mnt/root/addons
cp -vrf /run/live/medium/home/partimag/$IMAGE/debs /mnt/root/debs

echo "#!/bin/bash" > /mnt/1.sh
echo "mount /boot/efi" >> /mnt/1.sh
echo "grub-install --force --target i386-pc ${DISK_PATH}" >> /mnt/1.sh
echo "grub-install --force --target x86_64-efi --uefi-secure-boot ${DISK_PATH}" >> /mnt/1.sh
echo "dpkg -Ri /root/debs" >> /mnt/1.sh

find /mnt/root/addons/ -maxdepth 1 -type f -executable -print0 | while read -d $'\0' addon; do
    addon_filename=$(basename $addon)
    cron_filename=${addon_filename%%.*}
    echo "@reboot root /root/addons/${addon_filename}" >> "/mnt/etc/cron.d/${cron_filename}"
    echo "@reboot root /bin/rm -f /etc/cron.d/${cron_filename}" >> "/mnt/etc/cron.d/${cron_filename}"
done

shopt -s nullglob
configs=( /tmp/restore_config.* )
if ((${#configs[@]})); then
    first_config="${configs[0]}"
    mkdir -p /mnt/root/restore_configs
    cp -vf "$first_config" /mnt/root/restore_configs/
    echo "tar -C / -xvpf '/root/restore_configs/$(basename $first_config)'" >> /mnt/1.sh
    echo "rm -rf /root/restore_configs" >> /mnt/1.sh
fi

echo "umount /boot/efi" >> /mnt/1.sh

chroot /mnt /bin/bash /1.sh
rm /mnt/1.sh


chown -R root:root /mnt/root/
rm -rf /mnt/root/debs

umount /mnt/dev
umount /mnt/proc
umount /mnt

sync
echo "Waiting 10 seconds to shutdown..."
sleep 10
sync
halt -p
