#!/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() {
    echo "[$(/usr/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
}

STOP() { echo "==> $progname: error: $1" > "$errlog"; exit 0; }

Main() {
    local -r progname=${0##*/}
    local -r errlog="/var/log/$progname.errlog"
    local -r logfile="/var/log/$progname.log"
    local -r common_scripts_file="/usr/share/endeavouros/scripts/eos-script-lib-yad"

    [ "$EUID" = "0" ]                           || STOP "elevated privileges required."
    [ -r "$common_scripts_file" ]               || STOP "failed to read file $common_scripts_file."
    # shellcheck disable=SC1090
    source "$common_scripts_file" --limit-icons || STOP "failed to source file $common_scripts_file"

    eos_is_in_chroot && return 0

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

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

    # 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-open)
                IsRunningKernel linux && list_of_targets+=("$target")
                ;;
            nvidia-open-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 -qw 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[0]}" ] || return 0    # nothing to notify
    DoNotify
}

Main "$@"
