#!/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

while read -r line; do
    if [[ $line != */vmlinuz ]]; then
        # triggers when it's a change to usr/lib/dracut/modules.d/*
        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

    # remove the actual kernel and images for the package being removed
    kernel="/boot/vmlinuz-${pkgbase}"
    initramfs="/boot/initramfs-${pkgbase}.img"
    fallback_initramfs="/boot/initramfs-${pkgbase}-fallback.img"
    if [[ -e $kernel ]]; then
        # remove the installed kernel
        rm $kernel
    fi

    if [[ -e $initramfs ]]; then
        # remove the main image
        rm $initramfs
    fi
    if [[ -e $fallback_initramfs ]]; then
        # remove the fallback image
        rm $fallback_initramfs
    fi
done
