#!/bin/bash

# updater_action
#
# apt-notifier helper script to run
# refresh package lists and upgrade pakages
#
# User authentication is requested
#    - using gksu if installed and found at /usr/bin/gksu
#    - else using pkexec
#
# To work with pkexec a fixed script location is required
# within /usr/lib/apt-notifier/actions/
# for reload symlinked or copied as updater_reload_action
# for basic-upgrade as updater_basic-upgrade_action
# for full-upgrade as updater_full-upgrade_action

ME="${0}"
MODE=""
if [ "$1" = "run" ]; then
    MODE="run"
    shift
elif [ "$1" = "sudo-mode" ]; then
    MODE="sudo-mode"
    shift
fi

case "$ME" in
    *reload_action)
            ACTION=reload
            if [ "$MODE" = "run" ]; then
                RUN="/usr/lib/apt-notifier/bin/updater_reload_run"
            else
                RUN="/usr/lib/apt-notifier/bin/updater_reload"
            fi
            ;;
    *basic-upgrade_action)
            ACTION=basic-upgrade
            if [ "$MODE" = "run" ]; then
                RUN="/usr/lib/apt-notifier/bin/updater_basic-upgrade_run"
            else
                RUN="/usr/lib/apt-notifier/bin/updater_upgrade"
            fi
            ;;
    *full-upgrade_action)
            ACTION=full-upgrade
            if [ "$MODE" = "run" ]; then
                RUN="/usr/lib/apt-notifier/bin/updater_full-upgrade_run"
            else
                RUN="/usr/lib/apt-notifier/bin/updater_upgrade"
            fi
            ;;
    *)      echo "Error: no ACTION specified"
            exit 1
            ;;
esac

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

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


check_authenticator() {
    local authenticator 
    if [ "$ACTION" = "reload" ]; then
	    # 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    
    fi
   	if [ -z "$authenticator" ]; then
	    # 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
    fi
    echo "$authenticator"
}

if [ "$EUID" != 0 ]; then
    # normal user
    case $(check_authenticator) in
        *pkexec)
            EXEC=/usr/bin/pkexec
            if [ "$MODE" = "run" ]; then
                RUN="${RUN}"
            else
                RUN="${ME}"
            fi
            $EXEC "$RUN"
            ;;
        *gksu)
            sudo -k
            if [ "$MODE" = "run" ]; then
                /usr/bin/gksu "$RUN"
            else
                /usr/bin/gksu --sudo-mode  "$ME sudo-mode" && sudo "$ME"
            fi
            ;;
        *sudo)
            sudo -k
            sudo "$RUN"
            ;;
    esac
    exit $?
else
    #root user
    [ "$MODE" = "sudo-mode" ] && exit 0
    #check XDG_RUNTIME_DIR
    if [ "$XDG_RUNTIME_DIR" != "/run/user/0" ]; then
        export XDG_RUNTIME_DIR=/run/user/0
        [ -d $XDG_RUNTIME_DIR ] || mkdir -p $XDG_RUNTIME_DIR
        chmod 700 $XDG_RUNTIME_DIR
        chown 0:0 $XDG_RUNTIME_DIR
    fi
    
    #suppress "AT-SPI: Couldn't connect to accessibility bus" warnings
    #export NO_AT_BRIDGE=1
    
    #----------------------------------------------------------
    # put pattern list of environment variables we want get 
    # from users environment into an array
    __ENVIRONEMENT_PATTERN__=(
    DESKTOP_SESSION=
    KDE_FULL_SESSION=
    LANG=
    LANGUAGE=
    LC_[[:alpha:]]+=
    PWD=
    QT_[[:alnum:]_]+=
    XDG_CURRENT_DESKTOP=
    XDG_SESSION_TYPE=
    WAYLAND_DISPLAY=
    )
    # combine array into a string of space separated entries 
    __ENVIRONEMENT_PATTERN__="${__ENVIRONEMENT_PATTERN__[*]}"
    # replace spaces with pipe-symbole as pattern alternative
    __ENVIRONEMENT_PATTERN__="^(${__ENVIRONEMENT_PATTERN__// /|})"
    # read environment variables from users process environement table
    while read -r; do  
        IFS='=' read -r  k v  <<<"$REPLY" 
        # remove any 'bad' special char's like back-quotes and dollar sign
        v="${v//[\`\$]/}"
        # change to user working dir
        [ -z "${k##PWD=*}" ] && cd "$v" && continue
        # echo export $k="${v@Q}"  
        export $k="$v"  
    done < <( xargs -0 -L1 -a /proc/$PPID/environ \
            | grep -E "${__ENVIRONEMENT_PATTERN__}")

    unset k v
    unset __ENVIRONEMENT_PATTERN__
    
    exec "$RUN"
fi
exit 0
