#!/usr/bin/env bash

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

if [[ $install_all == 1 ]]; then
    reinstall-kernels
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
    for i in "${line[@]}"; do
        [[ "${i#initrd=*}" != "$i" ]] && continue
        [[ "${i#BOOT_IMAGE=*}" != "$i" ]] && continue
        BOOT_OPTIONS+="$i "
    done
    echo ${BOOT_OPTIONS} > /etc/kernel/cmdline
fi
