#!/bin/bash

linfo() {
    bold=$(tput bold)
    normal=$(tput sgr0)
    echo -e "${bold}[systemd-boot-friend-init]${normal} $*"
}

# Play it safe
set -e

# First source the config file
source /etc/systemd-boot-friend.conf

linfo "This script helps you to initialize systemd-boot on AOSC OS."

# Check if /boot/efi is mounted and has a vfat filesystem, according to UEFI specification.
if ! cat /proc/mounts | grep "$ESP_MOUNTPOINT vfat" > /dev/null 2>&1 ; then
    linfo "It seems that /boot/efi is not mounted or does not have vfat filesystem. Please mount your ESP to /boot/efi and make sure it has correct filesystem."
    exit 1
fi

if ! bootctl is-installed --esp-path="$ESP_MOUNTPOINT"; then
    linfo "Attempting to install systemd-boot..."
    if ! bootctl install --esp-path="$ESP_MOUNTPOINT"; then
        linfo "Failed to install systemd-boot. Exiting now."
        exit 1
    fi
fi


# Layout structure for trigger 
linfo "Creating folder structure for friend..."
mkdir -p "$ESP_MOUNTPOINT"/EFI/aosc
linfo "Calling systemd-boot-friend to install the kernels..."
systemd-boot-friend

# Then try to create systemd-boot config files.
linfo "Attempting to create systemd-boot boot entries..."
systemd-boot-mkconf 

linfo "Success! Now you should be able to boot the system via systemd-boot. Please make sure Linux Boot Manager is the first boot option in this computer's firmware setting."
linfo "If you want to change the kernel arguments, you can edit /boot/bootargs and re-run this script."
