#!/bin/bash

CHROOT=$(mount | grep proc | grep calamares | awk '{print $3}' | sed -e "s#/proc##g")

# Install luks utilities if needed.
# Also, set secure permissions for the initramfs if we're configuring
# full-disk-encryption. The initramfs is re-generated later in the
# installation process so we only set the permissions snippet without
# regenerating the initramfs right now:
if [ "$(mount | grep $CHROOT" " | cut -c -16)" = "/dev/mapper/luks" ]; then
    echo "UMASK=0077" > $CHROOT/etc/initramfs-tools/conf.d/initramfs-permissions
    chroot $CHROOT apt-get -y install cryptsetup-initramfs cryptsetup keyutils
fi

# 双内核的处理
systemArch=$(dpkg --print-architecture)
kerNum=$(ls -1 /boot/vmlinuz-* | wc -l)
unstallVmlinuzPath=$(ls /boot/vmlinuz-* | grep -v $(uname -r))
unstallInitrdPath=$(ls /lib/modules | grep -v $(uname -r))
if [[ $kerNum == 2 ]]; then
    # 获取包名
    unstallVmlinuzPkgName=$(echo $(grep -l $unstallVmlinuzPath /var/lib/dpkg/info/*.list) | sed 's%/var/lib/dpkg/info/%%g' | sed 's%.list%%g')
    unstallInitrdPkgName=$(echo $(grep -l $unstallInitrdPath /var/lib/dpkg/info/*.list) | sed 's%/var/lib/dpkg/info/%%g' | sed 's%.list%%g')
    DEBIAN_FRONTEND=noninteractive chroot $CHROOT apt-get -y autopurge $unstallInitrdPkgName -y
    DEBIAN_FRONTEND=noninteractive chroot $CHROOT apt-get -y autopurge $unstallVmlinuzPkgName -y
fi

echo "Running bootloader-config..."

if [ -d /sys/firmware/efi/efivars ]; then
    echo " * Installing grub-efi (uefi)..."
    DEBIAN_FRONTEND=noninteractive chroot $CHROOT apt-get -y install grub-efi-$systemArch | true
    DEBIAN_FRONTEND=noninteractive chroot $CHROOT apt-get -y install grub-efi | true
else
    echo " * install grub... (bios)"
    DEBIAN_FRONTEND=noninteractive chroot $CHROOT apt-get -y install grub-pc | true
fi

# Re-enable os-prober:
sed -i "s/#GRUB_DISABLE_OS_PROBER=false/# OS_PROBER re-enabled by GXDE Calamares installation:\nGRUB_DISABLE_OS_PROBER=false/g" $CHROOT/etc/default/grub
if [[ -f $CHROOT/usr/sbin/update-grub ]]; then
    chroot $CHROOT /usr/sbin/update-grub | true
fi
