#!/bin/bash

# updater_action
#
# mx-updater 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/mx-updater/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" = "sudo-mode" ]; then
    MODE="sudo-mode"
    shift
fi

case "$ME" in
    *reload_action)
        ACTION=reload
        RUN="/usr/lib/mx-updater/bin/updater_reload"
        ;;
    *basic-upgrade_action)
        ACTION=basic-upgrade
        RUN="/usr/lib/mx-updater/bin/updater_upgrade"
        ;;
    *full-upgrade_action)
        ACTION=full-upgrade
        RUN="/usr/lib/mx-updater/bin/updater_upgrade"
        ;;
    *)
        echo "Error: no ACTION specified"
        exit 1
        ;;
esac

check_authenticator() {
    if command -v pkexec > /dev/null; then
        # DEs with built-in or guaranteed polkit support: trust XDG_CURRENT_DESKTOP
        # directly without a process scan -- faster and handles agents whose names vary
        case "${XDG_CURRENT_DESKTOP:-}" in
            *GNOME*|*Cinnamon*|*Enlightenment*)
                echo "pkexec"
                return
                ;;
        esac
        # check if a known polkit agent is running for other DEs:
        # KDE, LXDE/LXQt, MATE, XFCE/Fluxbox (polkit-gnome runs on non-GNOME DEs too)
        local _agent
        for _agent in \
            polkit-kde-authentication-agent-1 \
            polkit-gnome-authentication-agent-1 \
            lxpolkit lxqt-policykit-agent mate-polkit; do
            if pgrep -u "$(id -u)" -f "$_agent" > /dev/null; then
                echo "pkexec"
                return
            fi
        done
    fi
    # pkexec not available or no polkit agent detected -- fall back
    if test -x /usr/bin/gksu; then
        echo "gksu"
    else
        echo "sudo"
    fi
}

if [ "$EUID" != 0 ]; then

    # normal user
    case $(check_authenticator) in
        *pkexec)
            pkexec "$ME"
            ;;
        *gksu)
            sudo -k
            /usr/bin/gksu --sudo-mode "$ME sudo-mode" && sudo "$ME"
            ;;
        *sudo)
            sudo -k
            sudo "$ME"
            ;;
    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__=(
    UPDATER_AUTO_CLOSE=
    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
