#!/bin/bash


upgrade_in_root_terminal="false"

check_authenticator() {
    local authenticator 
    
    # check users polkit agent is running
    if pgrep   -u $(id -u) -x  '(lx)?polkit.*' >/dev/null && \
       which pkexec > /dev/null; then
       authenticator=pkexec
    elif test -x /usr/bin/gksu; then
       authenticator=/usr/bin/gksu
    else
       # fallback to sudo
       authenticator=sudo
    fi
    echo "$authenticator"
    echo "pkexec"
}

# fallback to normal userterminal in case we need sudo
if [ "$upgrade_in_root_terminal" = "true" ] && \
   [ "$(check_authenticator)" = "sudo" ]; then
    upgrade_in_root_terminal="false"
fi

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

#APT_NOTIFIERRC="/home/$(logname)/.config/apt-notifierrc"
#UpgradeType=$(grep -oP '^UpgradeType=\K.*' "$APT_NOTIFIERRC" 2>/dev/null)
read -r UPGRADE_TYPE < <(get_config_item "upgrade_type" "full-upgrade")

if [ "$(id -u)"  != "0" ]; then
    #normal user
    upgrade_in_root_terminal="false"
    if [ "$upgrade_in_root_terminal" = "true" ]; then
        if [ "$UpgradeType" = "upgrade" ];   then
            RUN="/usr/lib/apt-notifier/actions/updater_basic-upgrade_action run"
        else
            RUN="/usr/lib/apt-notifier/actions/updater_full-upgrade_action run"
        fi
        $RUN
        exit $?
    fi  
fi


#ICON="${APT_NOTIFIER_CONFIG_ITEMS[window_icon]}"
#ICON_KDE="${APT_NOTIFIER_CONFIG_ITEMS[window_icon_KDE]}"
#DOMAIN="${APT_NOTIFIER_CONFIG_ITEMS[domain]}"
#ICON="${APT_NOTIFIER_CONFIG_ITEMS[window_icon]}"
#ICON_KDE="${APT_NOTIFIER_CONFIG_ITEMS[window_icon_KDE]}"
#DOMAIN="${APT_NOTIFIER_CONFIG_ITEMS[domain]}"
#["window_icon"]="/usr/share/icons/mx-updater.png"
#["window_icon_kde"]="/usr/share/icons/hicolor/scalable/mx-updater.svg"
#["domain"]="MX"

DOMAIN=MX
ICON="/usr/share/icons/mx-updater.png"
ICON_KDE="/usr/share/icons/hicolor/scalable/mx-updater.svg"

export TEXTDOMAIN="mx-updater"
UPDATER=$(gettext "MX Updater")


if [ "$UPGRADE_TYPE" = "upgrade" ];   then
    MSG="apt-get upgrade"
    UPGRADE=$(gettext "basic upgrade")
    RUN=/usr/lib/mx-updater/actions/updater_basic-upgrade_action
else
    MSG="apt-get full-upgrade"
    UPGRADE=$(gettext "full upgrade")
    RUN=/usr/lib/mx-updater/actions/updater_full-upgrade_action
fi

MSG="$UPGRADE"

TITLE="${UPDATER} -- ${UPGRADE}"

updater_show  "$MSG" "$RUN" "$TITLE" "$ICON" "$ICON_KDE"

exit
