#!/bin/bash
# -*- mode: sh; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
# vim: et sts=4 sw=4

#  SPDX-License-Identifier: LGPL-2.1+
#
#  Copyright © 2019-2021 Collabora Ltd.
#  Copyright © 2019-2021 Valve Corporation.
#
#  This file is part of steamos-customizations.
#
#  steamos-customizations is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation; either version 2.1 of the License,
#  or (at your option) any later version.

set -e

declare -A kern
all=0

while read -r line; do
    if [[ $line != */vmlinuz ]]; then
        # triggers when it's a change to usr/lib/dracut/modules.d/*
        all=1
        continue
    fi

    if ! read -r pkgbase > /dev/null 2>&1 < "${line%/vmlinuz}/pkgbase"; then
        # if the kernel has no pkgbase, we skip it
        continue
    fi

    # always install the kernel
    install -Dm644 "${line}" "/boot/vmlinuz-${pkgbase}"

    # compound args for each kernel
    kver="${line%/*}"
    kver="${kver##*/}"
    kern["${pkgbase}"]="$kver"
done

if (( all )) && compgen -G usr/lib/modules/"*"/vmlinuz > /dev/null; then
    unset kern
    declare -A kern
    while read -r line; do
    	if ! read -r pkgbase > /dev/null 2>&1 < "${line%/vmlinuz}/pkgbase"; then
    	    # if the kernel has no pkgbase, we skip it
    	    continue
    	fi

    	kver="${line%/*}"
    	kver="${kver##*/}"
    	kern["${pkgbase}"]="$kver"
    done < <(compgen -G usr/lib/modules/"*"/vmlinuz)
fi

for pkgbase in "${!kern[@]}"; do
    dracut --force --hostonly --persistent-policy by-partuuid "/boot/initramfs-$pkgbase.img" "${kern[$pkgbase]}"
    # Create a symlink as per https://github.com/dracutdevs/dracut/pull/1434
    # Otherwise dracut-initramfs-restore.sh will fail and thus our shutdown hooks/factory-reset
    # NOTE: should be part of Arch - https://bugs.archlinux.org/task/72185
    ln -sf "/boot/initramfs-$pkgbase.img" "/usr/lib/modules/${kern[$pkgbase]}/initrd"
    dracut --force --no-hostonly --persistent-policy by-partuuid "/boot/initramfs-$pkgbase-fallback.img" "${kern[$pkgbase]}"
done
