#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later

set -e

. /usr/share/debconf/confmodule

ARCH="$(archdetect)"

root_fs=$(mount | grep "on /target " | tail -n1 | cut -d' ' -f1)
if [ -z "$root_fs" ]; then
    echo "Could not determine root filesystem"
    exit 1
fi

root_uuid=$(blkid -s UUID -o value "$root_fs")
if [ -z "$root_uuid" ]; then
    echo "Could not determine root filesystem UUID"
    exit 1
fi

root_subvol_option=""
root_fs_type=$(blkid -s TYPE -o value "$root_fs")
if [ "$root_fs_type" = "btrfs" ]; then
    root_subvol_option=" rootflags=subvol=@rootfs"
fi

mkdir -p /target/etc/kernel/
echo "root=UUID=${root_uuid}${root_subvol_option}" > /target/etc/kernel/cmdline

db_get systemd-boot-installer/tries
tries=$((RET + 0))
if [ "$tries" -gt 0 ] && [ "$tries" -le 5 ]; then
    echo "$tries" > /target/etc/kernel/tries
fi

case $ARCH in
    amd64/efi)
        apt-install --allow-remove-essential systemd-boot shim-signed grub-efi-amd64-signed-
        ;;
    arm64/efi)
        apt-install --allow-remove-essential systemd-boot shim-signed grub-efi-arm64-signed-
        ;;
    *)
        apt-install systemd-boot
        ;;
esac
