#!/bin/bash

DoNotify() {
    local -r title="$1"
    local -r msg="$2"
    local urgency=normal
    local expiretime=0
    local user="$REBOOT_NOTIFICATION_USER"
    local icon=/usr/share/icons/Qogir/scalable/apps/system-reboot.svg
    [ -e $icon ] || icon=system-reboot
    [ "$REBOOT_EXPIRE_TIME" ] && expiretime="${REBOOT_EXPIRE_TIME}000"

    DEBUG "${FUNCNAME[0]} begin."

    # Configuration file may contain a user name to receive notifications,
    # then other users don't get them, and the notification can have a timer value
    # in the configuration file.

    if [ "$user" ] ; then
        if printf "%s\n" $(eos_GetUsers) | grep "$user" >/dev/null ; then
            :
        else
            WARNING "/usr/bin/users did not find username '$user'"
        fi
    fi

    DEBUG "user = '$user'; expiretime = '$expiretime'; urgency = '$urgency'"

    local cmd=(
        eos_notification_all           # function to notify all users
        "$icon"                        # icon
        "$urgency"                     # urgency
        "$expiretime"                  # expire time (not used with critical urgency!)
        "EndeavourOS notification"     # appname
        "$title"                       # title
        "$msg"                         # message
        RED                            # message color on TTY
        "$user"                        # may be empty
    )
    "${cmd[@]}"
    DEBUG "${FUNCNAME[0]} end."
}

WaitLoop() {
    local seconds_left="$1"
    local sleeptime="$2"
    local -r lockfile=/var/lib/pacman/db.lck
    local -r tasks="pacman,yay,paru"

    DEBUG "${FUNCNAME[0]} begin."

    while true ; do
        sleep "$sleeptime"
        ((seconds_left -= sleeptime))
        if [ $seconds_left -gt 0 ] && [ -e $lockfile ] && sudo fuser $lockfile &> /dev/null && ps -C $tasks &> /dev/null ; then
            if [ $seconds_left -gt 0 ] ; then
                INFO "${FUNCNAME[0]}: $(date): waiting, $seconds_left seconds left ..."
            elif [ -e $lockfile ] && sudo fuser $lockfile &> /dev/null ; then
                INFO "${FUNCNAME[0]}: $(date): waiting for the release of $lockfile ..."
            elif ps -C $tasks &> /dev/null ; then
                INFO "${FUNCNAME[0]}: $(date): waiting for all processes of [$tasks] to finish ..."
            fi
        else
            break
        fi
    done
    DEBUG "${FUNCNAME[0]} end."
}

ERROR()    { echo "==> $progname: ${FUNCNAME[0],,}: $1" >> "$infolog"; exit 0; }
WARNING()  { echo "==> $progname: ${FUNCNAME[0],,}: $1" >> "$infolog"; }
INFO()     { echo "==> $progname: ${FUNCNAME[0],,}: $1" >> "$infolog"; }
DEBUG()    { echo "==> $progname: ${FUNCNAME[0],,}: $1" >> "$infolog"; }

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 progname=${0##*/}
    local -r conffile=/etc/eos-reboot-recommended.conf
    local -r infolog="/var/log/$progname.log"
    local -r common_lib=/usr/share/endeavouros/scripts/eos-script-lib-yad

    rm -f "$infolog"
    DEBUG "$progname begin."

    # These 4 variables can be configured in $conffile.
    local REBOOT_MAX_TOTAL_WAIT=300
    local REBOOT_WAIT_DIFF=4
    local REBOOT_NOTIFICATION_USER=""
    local REBOOT_EXPIRE_TIME=""

    # shellcheck disable=SC1090
    [ -e "$conffile" ] && source "$conffile"
    systemctl disable --now eos-reboot-required.timer
    source $common_lib --limit-icons || ERROR "failed reading file $common_lib"
    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
    DEBUG "$progname end."
}

Wait_before_notifying "$@"
