#!/bin/bash

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

# Play it safe
set -e

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

if [[ -d "$ESP_MOUNTPOINT"/EFI/aosc ]]; then
    linfo "$ESP_MOUNTPOINT/EFI/aosc exists. Moving latest kernel and initramfs to this location."
    # First clean up the old ones
    DISTRO_NAME="aosc"

    # Remove old kernels and initramfs
    rm "$ESP_MOUNTPOINT"/EFI/aosc/initramfs-"$DISTRO_NAME"-*.img || true # It is possibel there's nothing yet
    rm "$ESP_MOUNTPOINT"/EFI/aosc/vmlinuz-"$DISTRO_NAME"-* || true

    for i in $(ls /usr/lib/modules | grep -v 'extramodules' | sort -V); do
        KERNEL_VER=$(echo $i | cut -d'-' -f1)
        DISTRO_NAME=$(echo $i | cut -d'-' -f2)
        KERNEL_FLAVOR=$(echo $i | cut -d'-' -f3)

        # Then move new kernels and initramfs to location
        linfo "Installing $i to $ESP_MOUNTPOINT/EFI/aosc..."

        if [[ -e /boot/vmlinuz-"$DISTRO_NAME"-"$KERNEL_FLAVOR"-"$KERNEL_VER" ]]; then
            # Old naming scheme
            cp /boot/vmlinuz-"$DISTRO_NAME"-"$KERNEL_FLAVOR"-"$KERNEL_VER" "$ESP_MOUNTPOINT"/EFI/aosc/vmlinuz-"$DISTRO_NAME"-"$KERNEL_FLAVOR"
        elif [[ -e /boot/vmlinuz-"$KERNEL_VER"-"$DISTRO_NAME"-"$KERNEL_FLAVOR" ]]; then
            # New namimg scheme
            cp /boot/vmlinuz-"$KERNEL_VER"-"$DISTRO_NAME"-"$KERNEL_FLAVOR" "$ESP_MOUNTPOINT"/EFI/aosc/vmlinuz-"$DISTRO_NAME"-"$KERNEL_FLAVOR"
        fi
        cp /boot/initramfs-"$KERNEL_VER"-"$DISTRO_NAME"-"$KERNEL_FLAVOR".img "$ESP_MOUNTPOINT"/EFI/aosc/initramfs-"$DISTRO_NAME"-"$KERNEL_FLAVOR".img
    done

    if [[ -e /boot/intel-ucode.img ]]; then
        linfo "intel-ucode detected. Installing..."
        cp /boot/intel-ucode.img "$ESP_MOUNTPOINT"/EFI/aosc/intel-ucode.img
    fi
else
    linfo "$ESP_MOUNTPOINT/EFI/aosc does not exist. Doing nothing."
    linfo "If you wish to use systemd-boot, run systemd-boot-friend-init."
    linfo "Or, if your ESP mountpoint is not at $ESP_MOUNTPOINT, please edit /etc/systemd-boot-friend.conf."
fi
