#!/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

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
else
    echo " * install grub... (bios)"
    DEBIAN_FRONTEND=noninteractive chroot $CHROOT apt-get -y install grub-pc
fi

# Re-enable os-prober:
sed -i "s/#GRUB_DISABLE_OS_PROBER=false/# OS_PROBER re-enabled by Debian Calamares installation:\nGRUB_DISABLE_OS_PROBER=false/g" $CHROOT/etc/default/grub

# Enable Plymouth splash on the installed system
sed -i 's/^GRUB_CMDLINE_LINUX_DEFAULT=.*/GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"/' $CHROOT/etc/default/grub

# Keep the graphical framebuffer mode so Plymouth can render its splash.
# Without this, GRUB switches to text mode before handing off to the kernel
# and Plymouth falls back to a hidden/text renderer, showing nothing.
grep -q 'GRUB_GFXPAYLOAD_LINUX' $CHROOT/etc/default/grub || \
    echo 'GRUB_GFXPAYLOAD_LINUX=keep' >> $CHROOT/etc/default/grub

# Set up recovery partition entry if present
ISO_MOUNT="/run/live/medium"
RECOVERY_DEV="$(blkid -L recovery 2>/dev/null || true)"

if [ -n "${RECOVERY_DEV}" ]; then
    echo " * Recovery partition found at ${RECOVERY_DEV}, setting up..."

    RECOVERY_MNT="$(mktemp -d /tmp/recovery-mount.XXXXXX)"
    mount "${RECOVERY_DEV}" "${RECOVERY_MNT}"

    cp "${ISO_MOUNT}/boot/recovery.vmlinuz" "${RECOVERY_MNT}/recovery.vmlinuz"
    cp "${ISO_MOUNT}/boot/recovery.initrd"  "${RECOVERY_MNT}/recovery.initrd"

    umount "${RECOVERY_MNT}"
    rmdir  "${RECOVERY_MNT}"

    cat >> "${CHROOT}/etc/grub.d/40_custom" << 'GRUBEOF'

menuentry "Recovery OS" {
    search --set=root --label recovery
    linux  /recovery.vmlinuz console=tty1 splash
    initrd /recovery.initrd
}
GRUBEOF
    echo " * Recovery GRUB entry written."
else
    echo " * WARNING: recovery partition not found — skipping recovery setup."
fi

# Rebuild initramfs so Plymouth is embedded for the installed system.
# Without this, the live-system initramfs is used and Plymouth's boot
# splash never appears (though shutdown/poweroff animations still work
# because those run from the installed rootfs directly).
chroot $CHROOT update-initramfs -u -k all

chroot $CHROOT /usr/sbin/update-grub
