#!/bin/bash

DoNotify() {
    local -r title="$1"
    local -r msg="$2"
    local icon=/usr/share/icons/Qogir/scalable/apps/system-reboot.svg
    [ -e $icon ] || icon=system-reboot

    local cmd=(
        eos_notification_all           # function to notify all users
        $icon                          # icon
        critical                       # urgency
        0                              # expire time (not used!)
        "'EndeavourOS notification'"   # appname
        "$title"                       # title
        "$msg"                         # message
        RED                            # message color on TTY
    )
    "${cmd[@]}"
}

WaitLoop() {
    local seconds_left="$1"
    local sleeptime="$2"
    local -r lockfile=/var/lib/pacman/db.lck
    local -r tmp=/tmp/tmp.sdoij87SA5hX
    rm -f $tmp

    while true ; do
        sleep $sleeptime
        ((seconds_left -= sleeptime))
        if [ $seconds_left -gt 0 ] && [ -e $lockfile ] && sudo fuser $lockfile &> /dev/null && ps -C pacman,yay,paru &> /dev/null ; then
            echo "$FUNCNAME: $(date): waiting ..." >> $tmp
        else
            break
        fi
    done
}

Wait_before_notifying() {
    # Wait for all pacman-like processes to finish before giving a notification.
    # Do this by detecting when the $lockfile disappears, but do not wait more
    # than $REBOOT_MAX_TOTAL_WAIT seconds.

    local -r conffile=/etc/eos-reboot-required.conf
    local REBOOT_MAX_TOTAL_WAIT=300          # can be configured in $conffile
    local REBOOT_WAIT_DIFF=4                 # can be configured in $conffile

    [ -e $conffile ] && source $conffile
    systemctl disable --now eos-reboot-required.timer
    source /usr/share/endeavouros/scripts/eos-script-lib-yad --limit-icons || return
    WaitLoop $REBOOT_MAX_TOTAL_WAIT $REBOOT_WAIT_DIFF  # max seconds to wait before notifying about recommended reboot

    [ -d /tmp ] && touch /tmp/reboot-recommended

    DoNotify "Reboot recommended!" "Reboot is recommended due to the upgrade of core system package(s)."
    systemctl disable --now eos-reboot-required.timer
}

Wait_before_notifying "$@"
