#!/bin/bash

DoNotify() {
    local -r msg="Reboot is recommended due to the upgrade of core system package(s)."
    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
        "Reboot recommended!"          # title
        "$msg"                         # message
        RED                            # message color on TTY
    )
    "${cmd[@]}"
}

InfoNotify() {
    local expiretime="${1}000"         # seconds to milliseconds
    local msg="$2"
    local icon=/usr/share/icons/Qogir/scalable/apps/info.svg
    [ -e $icon ] || icon=info
    local cmd=(
        eos_notification_all
        "$ICO_INFO"                    # icon
        normal                         # urgency
        "$expiretime"                  # expiretime
        "$progname"                    # appname
        "Notification from $progname"  # summary
        "$msg"                         # body
        RED
    )
    "${cmd[@]}"
}

Wait-for-some-processes() {
    # Wait for all pacman-like processes to finish.
    local -r progname=${0##*/}
    local notification_given=no
    local apps_to_wait="pacman,yay,paru,makepkg"

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

    systemctl disable --now eos-reboot-required.timer
    sleep 1

    while ps -C $apps_to_wait >/dev/null ; do
        if [ $notification_given = no ] ; then
            # show one waiting notification
            InfoNotify 4 "Waiting for apps [$apps_to_wait] to finish..."
            notification_given=yes
        fi
        sleep 1
    done
    DoNotify
}

Wait-for-some-processes "$@"
