#!/bin/bash

# load updater_config settings
unset APT_NOTIFIER_CONFIG_ITEMS
declare -A APT_NOTIFIER_CONFIG_ITEMS
UPDATER_CONFIG="/usr/lib/apt-notifier/bin/updater_config"
if [ -x "${UPDATER_CONFIG}" ]; then
    eval "APT_NOTIFIER_CONFIG_ITEMS=$(${UPDATER_CONFIG} --shell)"
fi

reload_in_root_terminal="${APT_NOTIFIER_CONFIG_ITEMS[reload_in_root_terminal]}"
allow_passwordless_reload_in_user_terminal="${APT_NOTIFIER_CONFIG_ITEMS[allow_passwordless_reload_in_user_terminal]}"

check_authenticator() {
    local authenticator

    # check pkexec is available
    if which pkexec > /dev/null; then
        # check users polkit agent is running
        if pgrep   -u $(id -u) -x  '(lx)?polkit.*' >/dev/null; then
           authenticator=pkexec
        # check polkit daemon is running as root
        elif pgrep -u 0  -x 'polkitd' >/dev/null                   && \
             [ "$reload_in_root_terminal" = "false" ]              && \
             [ "$allow_passwordless_reload_in_user_terminal" = "true" ]; then
             authenticator=pkexec
        fi
    fi

    if [ -z "$authenticator" ] &&  test -x /usr/bin/gksu; then
       authenticator=/usr/bin/gksu
    else
       # fallback to sudo
       authenticator=sudo
    fi
    echo "$authenticator"
}

# fallback to user_terminal in case we would use sudo
if [ "$reload_in_root_terminal" = "true" ] && \
   [ "$(check_authenticator)" = "sudo" ]; then
    reload_in_root_terminal=false
fi


if [ "$(id -u)"  != "0" ]; then
    #normal user
    if [ "$reload_in_root_terminal" = "true" ]; then
        RUN="/usr/lib/apt-notifier/actions/updater_reload_action run"
        $RUN
        exit $?
    fi
else
    RUN="/usr/lib/apt-notifier/actions/updater_reload"
fi

# load updater shell-libs settings
UPDATER_SHLIB=/usr/lib/apt-notifier/shlib/updater_shlib
if [ -f "$UPDATER_SHLIB" ]; then
      . "$UPDATER_SHLIB"
fi

ICON="${APT_NOTIFIER_CONFIG_ITEMS[window_icon]}"
ICON_KDE="${APT_NOTIFIER_CONFIG_ITEMS[window_icon_KDE]}"
DOMAIN="${APT_NOTIFIER_CONFIG_ITEMS[domain]}"
UPDATER=$(translate "MX Updater")
RELOAD=$(translate "Reload")

TITLE="${UPDATER}: $RELOAD"
RUN=/usr/lib/apt-notifier/actions/updater_reload_action
#MSG="apt-get update"
#MSG="$RELOAD"
#MSG="$TITLE"
MSG=""
updater_show  "$MSG" "$RUN" "$TITLE" "$ICON" "$ICON_KDE"

exit
