#!/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(s): ${list_of_targets[*]}" > $logfile
    chmod o-rwx $logfile
    systemctl enable --now eos-reboot-required.timer 2>/dev/null
}

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=""
    local list_of_targets=()

    # 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)
                # Note: only official kernels are checked.
                IsRunningKernel "$target" && list_of_targets+=("$target")
                ;;
            nvidia)
                IsRunningKernel linux && list_of_targets+=("$target")
                ;;
            nvidia-lts)
                IsRunningKernel linux-lts && list_of_targets+=("$target")
                ;;
            amd-ucode)
                [ "$(device-info --cpu)" = "AuthenticAMD" ] && list_of_targets+=("$target")
                ;;
            intel-ucode)
                [ "$(device-info --cpu)" = "GenuineIntel" ] && list_of_targets+=("$target")
                ;;
            btrfs-progs)
                # Notify only if btrfs is in use
                [ "$(/usr/bin/df -hT | awk '{print $2}' | grep -w btrfs)" ] && list_of_targets+=("$target")
                ;;
            wayland | egl-wayland)
                case "$XDG_SESSION_TYPE" in
                    x11) ;;
                    *) list_of_targets+=("$target") ;;
                esac
                ;;
            *)
                list_of_targets+=("$target")
                ;;
        esac
    done
    [ "$list_of_targets" ] && DoNotify || return 0    # 'return 0' here prevents the *false* error message from pacman
}

Main "$@"
