#!/bin/bash
#
# EOS update notifier for the current user.
#

#######################################################################
EOS_SCRIPTS_YAD=/usr/share/endeavouros/scripts/eos-script-lib-yad
test -r  $EOS_SCRIPTS_YAD || {
    echo "ERROR: cannot find $EOS_SCRIPTS_YAD" >&2
    exit 1
}
source /etc/eos-script-lib-yad.conf  # for EOS_ROOTER
source $EOS_SCRIPTS_YAD
unset EOS_SCRIPTS_YAD

export -f eos_yad
export -f eos_yad_terminal
export -f eos_yad_check_internet_connection
export -f eos_yad_GetArgVal
export -f eos_yad_RunCmdTermBash
export -f eos_yad_problem
export -f eos_yad_DIE
export -f eos_yad_WARN
#######################################################################

eos_un_log() {
    local date="$(/usr/bin/date '+%x %X')"
    echo ""       >> $EOS_UPDATE_NOTIFIER_LOG
    echo "$date"  >> $EOS_UPDATE_NOTIFIER_LOG
    echo "$@"     >> $EOS_UPDATE_NOTIFIER_LOG
}
export -f eos_un_log

echo2() { echo "$@" >&2 ; }
debug() {
    local DEBUG=1
    test "$verbosity" = "low" && DEBUG=0
    test $DEBUG -eq 1 && echo2 "$@"
    eos_un_log "$@"
}
log2() {
    echo2 "$@"
    eos_un_log "$@"
}

YadNonFocused() {
    local opts=(--no-focus --geometry=650x${height}+20+20 --title="$progname: updates available!")
    opts+=(--button="Dismiss!!Don't update, just close this window":1 --button="Update!!Close this window and update":0)
    opts+=(--fontname="$(FindAvailableMonoFont)")

    echo "$msg" | eos_yad --text-info "${opts[@]}" "$@"
}

ShowTray() {
    # Tray notification may have issues on EOS...
    eos_yad --notification --image="$ICO_UPDATE_AVAILABLE" \
            --text="$progname: $update_count $source updates are available at $date"
}
ShowNotify() {
    local expiretime="$1"   # milliseconds or 0 (=for a long time)
    local msg="$update_count $source updates are available"

    case "$expiretime" in
        *h) expiretime=$((1000*3600*${expiretime:: -1})) ;;
        *m) expiretime=$((1000*60*${expiretime:: -1})) ;;
        *s) expiretime=$((1000*${expiretime:: -1})) ;;
        0)  ;;
    esac

    case "$ShowWhatAboutUpdates" in
	number)
	    msg="$(printf "$update_count $source updates available at $date\n")" ;;
	packages)
	    msg="$(printf "$update_count $source updates available at $date:\n$pkgs\n")" ;;
    esac

    case "$ShowHowAboutUpdates" in
        notify)
            local bop=update
            local bname=Update
            local action=$(eos_notification \
                               "$ICO_UPDATE_AVAILABLE" \
                               "normal" \
                               "$expiretime" \
                               "EndeavourOS Update Notifier" \
                               "Updates available ($progname)" \
		               "$msg" \
                               "$bop=$bname")
            case "$action" in
                $bop)
                    if false ; then
                        local tmp_ufile=$(mktemp)
                        echo "$updates" > $tmp_ufile
                        UpdateInTerminal --nt --updates=$tmp_ufile
                    else
                        if [ "$CheckAurUpdates" = "yes" ] ; then
                            RunInTerminal eos-update --${AurUpdaterProg##*/}
                        else
                            RunInTerminal eos-update
                        fi
                    fi
                    ;;
            esac
            ;;
        "notify+tray")
            eos_notification \
                "$ICO_UPDATE_AVAILABLE" \
                "normal" \
                "$expiretime" \
                "EndeavourOS Update Notifier" \
                "Updates available ($progname)" \
		"$msg"
            ;;
    esac
}

ShowNonFocused() {
    local date="$(/usr/bin/date '+%x %X')"
    local source="$1"
    local pkgs="\n<tt>$updates</tt>"        # for notify and notify+tray

    if [ "$pkgsonly" = "yes" ] ; then       # cmd line options override config file options
        ShowHowAboutUpdates=window
        ShowWhatAboutUpdates=packages
    fi

    case "$ShowHowAboutUpdates" in
        notify)
            ShowNotify "$UN_NotifyTimeout"
            return 11       # don't start updating
            ;;
        tray)
            ShowTray
            ;;
        "notify+tray")
            ShowNotify "$UN_NotifyTrayTimeout"
            ShowTray
            ;;
        window)
            local height limit=400
            local msg

            case "$ShowWhatAboutUpdates" in
                packages)
                    pkgs="\n$updates"
                    height=$((10 * update_count + 120 + 40))
                    test $height -gt $limit && height=$limit
                    msg="$(printf "$update_count $source updates available at $date:\n$pkgs\n")"
                    YadNonFocused
                    ;;
                number | *)
                    height=100
                    msg="$(printf "$update_count $source updates available at $date.\n")"
                    YadNonFocused
                    ;;
            esac
            ;;
        "")
            log2 "Warning: variable 'ShowHowAboutUpdates' in file $EOS_UPDATE_NOTIFIER_CONF has no value."
            return 11
            ;;
        *)
            log2 "Warning: value '$ShowHowAboutUpdates' for 'ShowHowAboutUpdates' in file $EOS_UPDATE_NOTIFIER_CONF is not supported."
            return 11
            ;;
    esac
}

GetUpdateCount() {
    local retcode
    updates="$(/usr/bin/checkupdatesext)"
    retcode=$?
    if [ $retcode -eq 0 ] ; then
        update_count="$(echo "$updates" | wc -l)"
        update_count=$((update_count - 2))          # remove two lines of headers from checkupdatesext
    else
        update_count=0
    fi
}

Update_common() {
    # Check upstream updates first.

    local hasupdates=0
    local source=""
    local cmd=""
    local updates=""
    local update_count=0
    local extra_check=no
    local previous_check_time
    local secs=10

    if [ "extra_check" = "yes" ] ; then
        previous_check_time=$(/usr/bin/date +%s)
    fi

    SystemLockActive a || return
    echo2 "Checking for updates ..."
    GetUpdateCount

    if [ -n "$updates" ] ; then
        if lsmod | grep -w ^nvidia >/dev/null ; then
            local retvalue=0
            local tmpfile=$(mktemp)
            eos-kernel-nvidia-update-check --no-color $(echo "$updates" | tail -n +3 | awk '{print $1}') 2> $tmpfile || {
                cat $tmpfile | eos_yad_problem "Warning" --text="Update conflict detected. Do you want to continue (not recommended)?" \
                                               --width=800 --height=300 \
                                               --button=' Continue!$ICO_OPERATION_TEST!Ignore this warning and continue':2
                retvalue=$?
                case "$retvalue" in
                    0) retvalue=1 ;;    # eos_yad_problem returns 0 when quitting!
                    *) retvalue=0 ;;    # the above code returns 2 when continuing
                esac
            }
            rm -f $tmpfile
            [ $retvalue -ne 0 ] && exit 1
        fi

        if [ $update_focused -eq 0 ] ; then
            SystemLockActive b || return
            ShowNonFocused upstream || return 1    # returns 252 if window closed from X
            if [ "extra_check" = "yes" ] ; then
                if [ $(( $(/usr/bin/date +%s) - previous_check_time )) -gt $secs ] ; then
                    # Re-check for updates if more than $secs seconds elapsed from the first check.
                    echo2 "Re-checking for updates ..."
                    GetUpdateCount
                fi
            fi
        fi
        if [ -n "$updates" ] ; then              # some other process may have updated!
            ((hasupdates++))
            source=upstream
            if [ "$EOS_UPDATE_ARCH_KEYRING_FIRST" = "yes" ] ; then
                cmd="echo -n 'Updating, elevated privileges required. ' ; $EOS_ROOTER '/usr/bin/pacman -Sy --needed --noconfirm archlinux-keyring && /usr/bin/pacman -Su'"
            else
                cmd="echo -n 'Updating, elevated privileges required. ' ; $EOS_ROOTER '/usr/bin/pacman -Syu'"
            fi
            eos_un_log "$source updates available: $updates"
            eos_yad_RunCmdTermBash "echo $progname: updates from $source: ; echo \"$updates\" ; $cmd && printf '\n$source update done!\n' || printf '\n$source update failed.\n'"
        fi
    fi

    # Check AUR updates.

    if [ "$CheckAurUpdates" = "yes" ] ; then
        SystemLockActive c || return
        echo2 "Checking AUR updates ..."
        updates="$(/usr/bin/$AurUpdaterProg -Qua)"
    else
        updates=""
    fi
    if [ -n "$updates" ] ; then
        update_count="$(echo "$updates" | wc -l)"
        if [ $update_focused -eq 0 ] ; then
            SystemLockActive d || return
            ShowNonFocused AUR || return 1
            if [ "extra_check" = "yes" ] ; then
                updates="$(/usr/bin/$AurUpdaterProg -Qua)"    # may have been a long wait...
            fi
        fi
        if [ -n "$updates" ] ; then              # some other process may have updated!
            ((hasupdates++))
            cmd="/usr/bin/$AurUpdaterProg -Sua"                                        # potential problem for non-sudoers ...
            source=AUR
            eos_un_log "$source updates available: $updates"
            eos_yad_RunCmdTermBash "echo Updates from $source: ; echo \"$updates\" ; $cmd && printf '\n$source update done!\n' || printf '\n$source update failed.\n'"
        fi
    fi

    # Optionally, call additional (possibly user specified) updaters (e.g. a script to get flatpak updates)

    local external_updater_code=2             # Additional updater must return exit code like in 'checkupdates' (0=has updates, 1=failure, or 2=no updates)
    if [ -n "$AdditionalEosUpdater" ] ; then
        # Additional updater assumptions:
        #   - input:  the log file name (if needed, see also function eos_un_log() above)
        #   - output: exit code like in 'checkupdates' (see: man checkupdates)
        SystemLockActive e || return
        $AdditionalEosUpdater "$EOS_UPDATE_NOTIFIER_LOG"
        external_updater_code=$?
    fi
    if [ $hasupdates -ne 0 ] && [ "$SyncAfterUpdate" = "yes" ] ; then
        sync
    fi

    if [ $hasupdates -eq 0 ] && [ $external_updater_code -ne 0 ] ; then
        local msg="No updates available."
        debug "$msg"
        if [ "$verbosity" = "high" ] ; then
            if [ 1 -eq 1 ] ; then
                eos_yad --form \
                        --title="EndeavourOS update notifier" --text="$msg" \
                        --timeout=10 --timeout-indicator=left \
                        --image="$ICO_INFO" --width=350 --no-focus \
                        --button=yad-quit:0
            else
                echo "$msg" | \
                    eos_yad --text-info --title="EndeavourOS update notifier" --no-focus \
                            --height=100 --width=350 --timeout=10 --timeout-indicator=left \
                            --theme="Classic" --tail --button=yad-quit:0 --image="$ICO_INFO"
            fi
        fi
    fi
}

SystemLockActive() {
    if [ -e $system_lockfile ] ; then
        debug "Sorry, another program is currently using pacman databases."
        echo "Debug: ${FUNCNAME[1]} $@ stopped because of lock file." >> /tmp/.$progname.log
        return 1
    else
        return 0   # OK
    fi
}

CheckTimeoutVal() {
    local val="$1"

    if [ "${!val}" != "0" ] ; then
        if [ -n "$(echo "${!val}" | sed 's|[0-9][0-9]*[smh]||')" ] ; then
            eos_yad_DIE "'${!val}': unsupported value for variable $val."
        fi
    fi
}

Main2() {
    local CheckAurUpdates=yes
    # local CheckArchNewsForYou=yes
    # local ArchNewsProg=eos-arch-news
    # local ShowArchNewsPage=no
    local UN_NotifyTimeout=30s
    local UN_NotifyTrayTimeout=30s
    local SyncAfterUpdate=no
    local system_lockfile=/var/lib/pacman/db.lck
    local pids
    local AurUpdaterProg="$EOS_AUR_HELPER"

    # Make sure values from config files are valid.

    [ -n "$AurUpdaterProg" ] || AurUpdaterProg=yay

    CheckTimeoutVal UN_NotifyTimeout
    CheckTimeoutVal UN_NotifyTrayTimeout

    # Config file values should be OK.

    # check package manager lock
    SystemLockActive a || return

    Update_common
}

UseInitialFiles() {
    local configdir="$1"
    local progname="$2"
    local file

    pushd "$configdir" >/dev/null

    for file in $progname.timer $progname.service ; do
        [ -r /etc/skel/.config/systemd/user/$file ] || eos_yad_DIE "$FUNCNAME: file /etc/skel/.config/systemd/user/$file does not exist."
        rm -f $file.bak
        test -r $file && mv $file $file.bak
        cp /etc/skel/.config/systemd/user/$file .
    done

    popd >/dev/null
}

Initialize() {    # initialize service and timer for the current user

    DevLog "in $FUNCNAME"
    local modify_service=0
    local fetch_files=0
    local timer="$configdir"/$progname.timer
    local first_time_init_file="$HOME/.config/$progname.first_init"

    if [ ! -r "$first_time_init_file" ] ; then
        DevLog "first time initialization"
        echo "Remove this file if you wish to re-initialize $progname service." > "$first_time_init_file"
        fetch_files=1
    fi

    case "$arg" in
        -init-force | --init-force | -conf | --conf) modify_service=1 ;;
    esac
    case "$arg" in
        -init-force | --init-force) fetch_files=1 ;;
    esac
    if [ ! -r "$configdir"/$progname.service ] || [ ! -r "$timer" ] ; then
        fetch_files=1
    fi

    if [ "$fetch_files" = "1" ] || [ "$modify_service" = "1" ]
    then
        DevLog "get new service files"
        systemctl --user status $progname.timer >/dev/null && {
            systemctl --user stop    $progname.timer
            systemctl --user disable $progname.timer
        }
        test "$fetch_files" = "1" && UseInitialFiles "$configdir" "$progname"
        case "$arg" in
            -conf | --conf)
                # add any missing setting under [Timer] (in reverse order)
                [ -n "$(grep ".*RandomizedDelaySec="   "$timer")" ] || sed -i "$timer" -e "/^\[Timer\]/a \RandomizedDelaySec=$randomizeddelaysec"
                [ -n "$(grep ".*Persistent="           "$timer")" ] || sed -i "$timer" -e "/^\[Timer\]/a \Persistent=$persistent"
                [ -n "$(grep ".*OnCalendar="           "$timer")" ] || sed -i "$timer" -e "/^\[Timer\]/a \OnCalendar=$oncalendar"
                [ -n "$(grep ".*OnStartupSec="         "$timer")" ] || sed -i "$timer" -e "/^\[Timer\]/a \OnStartupSec=$onstartupsec"

                # remove possible old stuff
                sed -i "$timer" -e "s|^# Persistent=true||"

                # write new settings
                case "${onstartupsec,,}" in
                    ""|false) sed -E -i "$timer" -e "s|.*OnStartupSec=.*|# OnStartupSec=|" ;;
                    *)        sed -E -i "$timer" -e "s|.*OnStartupSec=.*|OnStartupSec=30sec|" ;;
                esac
                sed -i "$timer" \
                    -e 's|^OnCalendar=.*$|OnCalendar='"$oncalendar"'|' \
                    -e "s|^Persistent=.*|Persistent=$persistent|"
                ;;
        esac
        systemctl --user enable $progname.timer
        systemctl --user start  $progname.timer
        systemctl --user daemon-reload
        debug "New '$configdir/$progname.service' successfully set up."
        debug "New '$configdir/$progname.timer' successfully set up."
        debug "$progname service initialized for user '$(basename "$HOME")'."
    fi
}

CheckInternetConnection() {
    local wait_rounds="$1"
    local one_wait="$2"

    # default is max two minutes wait
    test -z "$wait_rounds" && wait_rounds=30
    test -z "$one_wait"    && one_wait=4s

    # Wait for internet connection max "$wait_rounds * $one_wait" seconds.

    eos_yad_check_internet_connection no_fail_dialog $wait_rounds $one_wait || {
        if [ "$verbosity" = "high" ] ; then
            if [ 0 -eq 1 ] ; then
                echo "Internet connection is not available!" | \
                    eos_yad_problem "Warning from eos-update-notifier" --width=400 --height=200 &
            else
                eos_notification "dialog-warning" "normal" "60000" "eos-update-notifier" \
                                 "Warning from eos-update-notifier" "Internet connection is not available!"
            fi
        fi
        debug "Warning: eos-update-notifier: internet connection is not available!"
        return 1
    }
}

Configure() {
    local result retval cmd=()

    case "0" in
        0)
            local times="hourly!daily!weekly!monthly"
            case "$oncalendar" in
                hourly | daily | weekly | monthly) ;;
                *) oncalendar=daily ;;
            esac
            times=$(echo "$times" | sed "s|$oncalendar|^$oncalendar|")
            # temporarily set this to boolean value:
            case "${onstartupsec,,}" in
                ""|false) onstartupsec=false ;;
                *)        onstartupsec=true ;;
            esac
            cmd=(
                eos_yad
                --form
                --title="Configure update checking"
                --text="$progname: configure the schedule of system update checks."
                --image="$ICO_PREFERENCES_SYSTEM"
                --field="Check period!How often checks will be executed":CB "$times"
                --field="Check always after system startup!Enable/disable update check right after boot":CHK "$onstartupsec"
                --field="Persistent!When selected, if a check is missed, the check will be executed as soon as possible":CHK "$persistent"
                --button=yad-ok
            )
            result=$("${cmd[@]}")
            retval=$?
            [ "$retval" -eq 0 ] || return 1

            oncalendar=$(  echo "$result" | cut -d'|' -f1)
            onstartupsec=$(echo "$result" | cut -d'|' -f2)
            persistent=$(  echo "$result" | cut -d'|' -f3 | tr '[:upper:]' '[:lower:]')
            ;;
        1)
            # backup old timer file:
            cp $configdir/$progname.timer $configdir/$progname.timer.bak."$(date +%x-%X)"

            local xx
            local periods=(
                hourly daily weekly monthly
                # quarterly semiannually yearly   # not sensible values!?
            )
            local defaultperiod=daily
            cmd=(
                eos_yad --list --radiolist --column=Select --column=Period --width=400 --height=250
                --image="$ICO_PREFERENCES_SYSTEM"
                --title="Configure update check schedule"
                --text="Select the period for system updates"
                --button="Set to default":10 --button=yad-cancel:1 --button=yad-ok:0
            )
            # Convert from the old settings:
            case "$oncalendar" in
                hourly | daily | weekly | monthly) ;;
                *) oncalendar="$defaultperiod" ;;
            esac
            # build selections:
            for xx in "${periods[@]}" ; do
                case "$xx" in
                    "$oncalendar") cmd+=(true  "$xx") ;;
                    *)             cmd+=(false "$xx") ;;
                esac
            done

            # ask user
            result=$("${cmd[@]}")
            retval=$?

            case "$retval" in
                0)  oncalendar=$(echo "$result" | cut -d '|' -f 2) ;;
                10) oncalendar="$defaultperiod" ;;
                1) return 1 ;;
            esac
            ;;
        2)
            local current_interval=$(echo "$oncalendar" | cut -d ':' -f 1 | cut -d '/' -f 2)
            local current_initial=$( echo "$oncalendar" | cut -d ':' -f 1 | cut -d '/' -f 1)
            local current_minute=$(  echo "$oncalendar" | cut -d ':' -f 2)

            local tips="Tips:\n- <i>Initial hour</i> means the first triggering hour within 24 hours.\n"
            tips+="- <i>Minute offset</i> is the current randomized minute value and cannot be changed.\n"

            result=$(
                eos_yad --form --title="Configure update check schedule" --width=400 \
                        --text="$tips" --window-icon=$EOS_WICON \
                        --field="Interval in hours":num           $current_interval \
                        --field="Initial hour":num                $current_initial \
                        --field="Minute offset":ro                $current_minute \
                        --button="Set to defaults":10 --button=yad-cancel:1 --button=yad-ok:0
                  )
            retval=$?
            test $retval -eq 1 && return 1

            local new_interval=$(echo "$result" | cut -d '|' -f 1)
            local new_initial=$( echo "$result" | cut -d '|' -f 2)
            local new_minute=$(shuf -i0-59 -n1)                      # try make users start at different times...

            case $retval in
                10)
                    local default_interval=2
                    local default_initial=0
                    local default_minute=$(shuf -i0-59 -n1)          # try make users start at different times...
                    
                    if [ $new_interval -eq $default_interval ] && [ $new_initial -eq $default_initial ] && [ $new_minute -eq $default_minute ]
                    then
                        return  # nothing to do
                    fi
                    oncalendar="$default_initial/$default_interval:$default_minute:00"
                    ;;
                0)  
                    if [ $new_interval -eq $current_interval ] && [ $new_initial -eq $current_initial ] && [ $new_minute -eq $current_minute ]
                    then
                        return  # nothing to do
                    fi
                    oncalendar="$new_initial/$new_interval:$new_minute:00"
                    ;;
            esac
            ;;
    esac

    echo2 "New OnCalendar value: $oncalendar"
    Initialize
}

Usage() {
    local iwt="$initial_waittime"
    test -z "$iwt" && iwt="[none]"

    local prog_name="$progname"
    test -z "$prog_name" && prog_name="$(basename $0) [basename]"

    cat <<EOF


Usage: $prog_name [options]

Options:
   -init        Initialize $prog_name systemd service for current user.
   -init-force  Same as -init, but may overwrite existing user service files.
   -conf        Configure the schedule of checking for the updates.
   -show-timer  Show the status of the systemd timer.
   -iw=X        Initial sleep time. Value syntax from 'sleep' program.
                Default: $iwt.
   -nw=X        Max time (seconds) to show the "No updates available" window.
                Default: $no_updates__indicator_wait_time.
   -q           Be quieter with dialogs.
   --changelog  Show the changelog of this package.
EOF
}

InitialWait() {
    test -n "$initial_waittime" && {
        #debug "Initial wait for $initial_waittime"
        sleep "$initial_waittime"
    }
}

DevLog() {
    if [ "$dev_log" = "yes" ] ; then
        echo "$(date "+%Y%m%d %H:%M:%S"); $@" >> $dev_logfile
    fi
}

yad_infomsg() {
    local msg="$1"
    local title="$2"
    test -n "$title" || title="Info"
    echo2 "$title: $msg"
    eos_yad --form --text="$msg" --title="$title" --button=yad-ok:0 --image="$ICO_INFO"
}

Main()
{
    local progname=eos-update-notifier

    if [ -x /usr/bin/calamares ] && [ "$LOGNAME" = "liveuser" ] ; then
        echo "==> Stopping $progname while installing."
        return 0
    fi

    AssignIconVariables_in_eos_bash_shared                                  # get common icons

    yad_missing_check $progname

    local dev_log=no
    local dev_logfile=/tmp/$progname.dev_log
    local configdir="$HOME/.config/systemd/user"
    local initial_waittime="5s"  # was 10s
    local loop_waittime=60m
    local no_updates__indicator_wait_time=10
    local verbosity=high
    local mode=onetimer  # "onetimer" or "loop"
    local systemd=0
    local newsdays=30
    local arg
    local initialize=""
    local update_focused=0
    local pkgsonly=no
    local EOS_UPDATE_NOTIFIER_CONF=/etc/$progname.conf
    #local NOTIFIER_LOG_FILE=/tmp/$progname.log

    local oncalendar="$(  grep ".*OnCalendar="   $configdir/$progname.timer 2>/dev/null | cut -d '=' -f 2)"
    local onstartupsec="$(grep ".*OnStartupSec=" $configdir/$progname.timer 2>/dev/null | cut -d '=' -f 2)"
    local persistent="$(  grep ".*Persistent="   $configdir/$progname.timer 2>/dev/null | cut -d '=' -f 2)"
    local -r randomizeddelaysec=10min

    [ -n "$oncalendar" ]   || oncalendar=daily
    [ -n "$persistent" ]   || persistent=false
    case "${onstartupsec,,}" in
        ""|false) onstartupsec="" ;;
        *)        onstartupsec=30sec ;;
    esac

    mkdir -p "$configdir"

    rm -f /tmp/$progname.log.*
    export EOS_UPDATE_NOTIFIER_LOG=$(mktemp /tmp/$progname.log.XXXXXXXX)

    DevLog "main loop starting"

    [ -r $EOS_UPDATE_NOTIFIER_CONF ] && source $EOS_UPDATE_NOTIFIER_CONF

    # ICO_UPDATE_AVAILABLE=$(eos_icon_path apps software-update-available)    # app specific icons
    case "$UpdateNotifyIcon" in
        /*) ICO_UPDATE_AVAILABLE="$UpdateNotifyIcon" ;;                        # ICO_UPDATE_AVAILABLE=/usr/share/icons/Qogir/scalable/apps/software-update-available.svg
        *)  ICO_UPDATE_AVAILABLE=$(eos_icon_path apps "$UpdateNotifyIcon") ;;
    esac

    for arg in "$@" ; do
        case "$arg" in
            -init | --init | -init-force | --init-force)
                DevLog "got option '$arg'"
                initialize="$arg"
                ;;
            -conf | --conf)
                Configure
                return
                ;;
            -show-timer | --show-timer)
                RunInTerminal "systemctl --user status eos-update-notifier.timer"
                return
                ;;
            --changelog)
                $(eos_select_browser) $(eos-github2gitlab https://github.com/endeavouros-team/PKGBUILDS/commits/master/eos-update-notifier)
                return
                ;;
            -iw=*)
                initial_waittime="$(eos_yad_GetArgVal "$arg")"
                ;;
            -lwt=*)
                loop_waittime="$(eos_yad_GetArgVal "$arg")"
                ;;
            -nw=*)
                no_updates__indicator_wait_time="$(eos_yad_GetArgVal "$arg")"
                ;;
            -news=*)
                newsdays="$(eos_yad_GetArgVal "$arg")"
                ;;
            -q | --quiet)
                verbosity=low
                ;;
            --pkgsonly)
                pkgsonly=yes
                initial_waittime=0
                ;;
            -systemd | --systemd)
                systemd=1
                ;;
            -update-focused | --update-focused)
                # this time we will steal focus (earlier we just showed there are updates)
                update_focused=1
                ;;
            -mode=*)
                mode="$(eos_yad_GetArgVal "$arg")"
                case "$mode" in
                    onetimer | loop) ;;
                    *) eos_yad_DIE "Unsupported mode '$mode'." ; break ;;
                esac
                ;;
            --foo)
                dev_log=yes
                ;;
            -*)
                eos_yad_DIE "Unsupported option '$arg'."
                ;;
            *)
                eos_yad_DIE "Unsupported parameter '$arg'."
                ;;
        esac
    done
    if [ $systemd -eq 1 ] ; then
        # make sure to have proper options when systemd called
        verbosity=low
        mode=onetimer
    fi

    case "$initialize" in
        -init-force | --init-force) ;;
        *) InitialWait ;;
    esac

    # Now internet connection is required.
    CheckInternetConnection || return 1

    DevLog "has internet connection"
    case "$initialize" in
        -init-force | --init-force | -init | --init) Initialize ; return ;;
    esac

    while true ; do
        Main2
        test "$mode" = "onetimer" && break
        sleep "$loop_waittime"
    done
}

Main "$@"
