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

# Pass on the user's boot parameters (and debian-installer/add-kernel-opts),
# as grub-installer does
user_params=$(echo $(user-params)) || true
got_quiet=""
for u in $user_params; do
    [ "$u" != quiet ] || got_quiet=1
done
[ -n "$got_quiet" ] || user_params="quiet${user_params:+ $user_params}"

mkdir -p /target/etc/kernel/
echo "root=UUID=${root_uuid}${root_subvol_option} ${user_params}" > /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)
        in-target sh -c "debconf-apt-progress --no-progress --logstderr -- apt-get -q -y --allow-remove-essential install systemd-boot shim-signed grub-efi-amd64-signed-"
        ;;
    arm64/efi)
        in-target sh -c "debconf-apt-progress --no-progress --logstderr -- apt-get -q -y --allow-remove-essential install systemd-boot shim-signed grub-efi-arm64-signed-"
        ;;
    *)
        apt-install systemd-boot
        ;;
esac
