#!/usr/bin/env bash

while read -r line; do
    if [[ $line != */vmlinuz ]]; then
        # this means this is something other than a kernel change
        all=1
        break
    fi

    version=$(basename "${line%/vmlinuz}")
    if [[ $1 == "remove" ]]; then
        echo ":: kernel-install removing kernel $version"
        kernel-install remove "${version}"
    elif [[ $1 == "add" ]]; then
        echo ":: kernel-install installing kernel $version"
        kernel-install add "${version}" "${line}"
    else
        echo ":: Invalid option passed to kernel-install script"
    fi
done

if [[ $all == 1 ]]; then
    # Run kernel-install for all the installed kernels
    while read -r kernel; do
        kernelversion=$(basename "${kernel%/vmlinuz}")
        echo "Running kernel-install for ${kernelversion}"
        kernel-install add ${kernelversion} ${kernel}
    done < <(find /usr/lib/modules -maxdepth 2 -type f -name vmlinuz)
fi

# first check if we are running in a chroot
if [ "$(stat -c %d:%i /)" != "$(stat -c %d:%i /proc/1/root/.)" ]; then
    echo 'Running in a chroot, skipping cmdline generation'
    exit 0
fi

# If needed, set /etc/kernel/cmdline to enable kernel-install in a chroot
if [[ ! -e /etc/kernel/cmdline ]]; then
    mkdir -p /etc/kernel
    
    BOOT_OPTIONS=""
    read -r -d '' -a line < /proc/cmdline
    # Add the items from /proc/cmdline excluding the items we don't need
    for i in "${line[@]}"; do
        [[ "${i#initrd=*}" != "$i" ]] && continue
        [[ "${i#BOOT_IMAGE=*}" != "$i" ]] && continue
        [[ "${i#systemd.machine_id=*}" != "$i" ]] && continue
        BOOT_OPTIONS+="$i "
    done
    echo ${BOOT_OPTIONS} > /etc/kernel/cmdline
fi
