#!/bin/bash

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

# Play it safe
set -e

# Load config
source /etc/systemd-boot-friend.conf

# Probe PARTUUID for /
if ! ROOT_PARTITION=$(cat /proc/mounts | grep " / " | awk '{print $1}'); then
    linfo "Failed to probe root partition, you may want to manually edit $ESP_MOUNTPOINT/loader/entries/aosc-*.conf manually later."
    ROOT_PARTUUID="EDITME"
elif ! ROOT_PARTUUID=$(blkid --match-tag PARTUUID --output value "$ROOT_PARTITION"); then
	linfo "Failed to probe root partition, you may want to manually edit $ESP_MOUNTPOINT/loader/entries/aosc-*.conf manually later."
	ROOT_PARTUUID="EDITME"
fi

for i in $(ls /usr/lib/modules | grep -v 'extramodules'); do
    KERNEL_VER=$(echo $i | cut -d'-' -f1)
    DISTRO_NAME=$(echo $i | cut -d'-' -f2)
    KERNEL_FLAVOR=$(echo $i | cut -d'-' -f3)
    
    ENTRY_FILE="$ESP_MOUNTPOINT/loader/entries/$DISTRO_NAME-$KERNEL_FLAVOR.conf"
    if [[ -e "$ENTRY_FILE" ]] || [[ $1 != "-f" ]]; then
        linfo "$ENTRY_FILE already existed. Doing nothing on this file."
        linfo "If you wish to override the file, specify -f and run again."
        break
    fi
    
    linfo "Creating boot entry for $i at $ENTRY_FILE..."
    echo "title AOSC OS ($KERNEL_FLAVOR)" > "$ENTRY_FILE" # Empty the file here
    echo "linux /EFI/aosc/vmlinuz-$DISTRO_NAME-$KERNEL_FLAVOR" >> "$ENTRY_FILE"
    if [[ -e /boot/efi/EFI/aosc/intel-ucode.img ]]; then
        echo "initrd /EFI/aosc/intel-ucode.img" >> "$ENTRY_FILE"
    fi
    echo "initrd /EFI/aosc/initramfs-$DISTRO_NAME-$KERNEL_FLAVOR.img" >> "$ENTRY_FILE"
    echo "options root=PARTUUID=$ROOT_PARTUUID rw $BOOTARG" >> "$ENTRY_FILE"
done
