#!/bin/bash

# Avoid unnecessary reboots: don't notify if an updated package is
# - not currently running (e.g. alternative kernel)
# - not in use (e.g. alternative driver)

IsRunningKernel() {
    if [ -z "$running_kernel" ] ; then
        running_kernel=$(eos_running_kernel)
    fi
    test "$1" = "$running_kernel"
}

DoNotify() {
    local logfile=/var/log/reboot-recommendation-trigger.log
    echo "[$(/bin/date "+%x %X")] Reboot recommendation triggered by updating package: $target" > $logfile
    chmod o-rwx $logfile
    systemctl enable --now eos-reboot-required.timer 2>/dev/null
    sleep 1
    exit 0
}

Main() {
    [ "$EUID" = "0" ] || return 0    # require elevated privileges

    source /usr/share/endeavouros/scripts/eos-script-lib-yad --limit-icons || return 0

    eos_is_in_chroot && return 0

    [ "$EOS_REBOOT_RECOMMENDING" = "no" ] && return 0

    local targets=$(cat)  # list of updated package names from the hook (stdin)
    local target
    local running_kernel=""

    # do not notify if the updated package is not in use
    for target in $targets ; do
        case "$target" in
            linux | linux-lts | linux-zen | linux-hardened | linux-rt | linux-rt-lts | linux-lts?? | linux-lts???)
                # Note: only official and older LTS kernels are checked.
                if IsRunningKernel "$target" ; then
                    DoNotify
                fi
                ;;
            nvidia)
                if IsRunningKernel linux ; then
                    DoNotify
                fi
                ;;
            nvidia-lts)
                if IsRunningKernel linux-lts ; then
                    DoNotify
                fi
                ;;
            amd-ucode)
                if [ "$(device-info --cpu)" = "AuthenticAMD" ] ; then
                    DoNotify
                fi
                ;;
            intel-ucode)
                if [ "$(device-info --cpu)" = "GenuineIntel" ] ; then
                    DoNotify
                fi
                ;;
            btrfs-progs)
                # Notify only if btrfs is in use
                if [ -n "$(/usr/bin/df -hT | awk '{print $2}' | grep -w btrfs)" ] ; then
                    DoNotify
                fi
                ;;
            wayland | egl-wayland)
                case "$XDG_SESSION_TYPE" in
                    x11) ;;
                    *) DoNotify ;;
                esac
                ;;
            *)
                DoNotify
                ;;
        esac
    done
}

Main "$@"
