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

set -e

. /usr/share/debconf/confmodule

db_get systemd-boot-installer/skip
if [ "$RET" = true ]; then
	exit 1
fi

ARCH="$(archdetect)"

case $ARCH in
    amd64/efi|arm64/efi|riscv64/efi)
	;;
    *)
	logger -t systemd-boot-installer "systemd-boot is only usable on 64bit EFI systems, not $ARCH"
	exit 1
	;;
esac

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

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

# TODO: drop once debian-installer-utils provides this
if ! cut -d" " -f2 /proc/mounts | sort | uniq | grep -q '^/target/sys$'; then
	mount -t sysfs sysfs /target/sys
	mount -t efivarfs efivarfs /target/sys/firmware/efi/efivars
	trap "umount /target/sys/firmware/efi/efivars /target/sys" EXIT
elif ! cut -d" " -f2 /proc/mounts | sort | uniq | grep -q '^/target/sys/firmware/efi/efivars$'; then
	mount -t efivarfs efivarfs /target/sys/firmware/efi/efivars
	trap "umount /target/sys/firmware/efi/efivars" EXIT
fi

apt-install systemd-boot
