#!/bin/bash

# MX Linux mx-installer pkexec wrapper to retain QT environment
# Usage:
#        minstall-launcher (formerly minstall-pkexec)
# based on mx-pkexec wrapper

# exit early if not live or parameter given
if [ -n "$1" ] || { ! grep -sq 'lowerdir=/live/linux' /proc/mounts && ! grep -sq 'lowerdir=/run/archiso/airootfs' /proc/mounts; }; then
    echo ""
    echo "INFORMATION: Non-live enviroment or options not supported"
    echo "             use alternate authentication to launch installer"
    echo "             sudo minstall [OPTIONS]"
    echo ""
    exit 1
fi

##launch installer

if [ "$EUID" != 0 ]; then
    # normal user

    ##disable Xfce automount features
    if command -v xfconf-query >/dev/null; then
        unset AUTO PROP XFCQ
        XFCQ="xfconf-query --channel thunar-volman"
        AUTO=($(${XFCQ} --list 2>/dev/null | grep /auto))
        PROP=()
        for prop in "${AUTO[@]}";  do
            auto=$(${XFCQ} --property $prop)
            [ "$auto" = "true" ] || continue
            ${XFCQ} --property "$prop" --set "false"
            PROP+=("$prop")
        done
    fi
    ###end Xfce automount feature

    # wayland fix (AK-47)
    if [ x"$WAYLAND_DISPLAY" != "x" ] && [ -n "${WAYLAND_DISPLAY##/*}" ]; then
        export WAYLAND_DISPLAY=$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY
    fi

    AUTHENTICATION="$(grep -i '^\s*Authentication\s*=' /usr/share/gazelle-installer-data/installer.conf |cut -d= -f2)"
    if [ -n "$AUTHENTICATION" ]; then
        set -- $AUTHENTICATION
        if ! command -v "$1" >/dev/null 2>&1; then
            AUTHENTICATION=""
        fi
    fi

    if [ -z "$AUTHENTICATION" ]; then
        if command -v su-to-root >/dev/null 2>&1; then
            AUTHENTICATION="su-to-root -X -c"
        elif command -v pkexec >/dev/null 2>&1; then
            PKEXEC_CMD="pkexec"
            if pkexec --help 2>/dev/null | grep -q -- '--action-id'; then
                PKEXEC_CMD="pkexec --action-id org.mxlinux.minstall-launcher"
            fi
            AUTHENTICATION="$PKEXEC_CMD env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY"
        elif command -v sudo >/dev/null 2>&1; then
            AUTHENTICATION="sudo -E"
        else
            echo "No authentication helper found (tried su-to-root, pkexec, sudo)." >&2
            exit 1
        fi
    fi

    $AUTHENTICATION /usr/bin/minstall-launcher

    ##re-enable Xfce automount feature, if it was enabled in the first place
    if command -v xfconf-query >/dev/null; then
        for prop in "${PROP[@]}"; do
            ${XFCQ} --property "$prop" --set "true"
        done
    fi
    ##end Xfce automount feaure

else
    # root user

    # restrict PATH for security
    if [ -e /run/archiso/airootfs ] || [ ! -d /usr/sbin ]; then
        PATH="/usr/bin:/usr/local/bin"
    else
        PATH="/usr/bin:/usr/sbin:/usr/local/bin"
    fi

    # put pattern list of environment variables we want get from users environment into array
    __ENVIRONEMENT_PATTERN__=(
        DESKTOP_SESSION
        HOME=
        KDE_FULL_SESSION=
        LANG=
        LANGUAGE=
        LC_
        QT_
        XCURSOR_
        XDG_
        WAYLAND_
    )

    # 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//[\`\$]/}"
        export $k="$v"
    done < <( xargs -0 -L1 -a /proc/$PPID/environ \
            | grep -E "${__ENVIRONEMENT_PATTERN__}")

    unset k v
    unset __ENVIRONEMENT_PATTERN__

    # set XDG_RUNTIME_DIR - create a valid runtime dir
    if [ "$XDG_RUNTIME_DIR" != "/run/user/0" ]; then
        XDG_RUNTIME_DIR=/run/user/0
        export XDG_RUNTIME_DIR
        [ -d $XDG_RUNTIME_DIR ] || mkdir -p $XDG_RUNTIME_DIR
        chmod 700 $XDG_RUNTIME_DIR
        chown 0:0 $XDG_RUNTIME_DIR
    fi

    RUN="/usr/bin/minstall"
    echo Starting "$RUN"
    # always change working directory to /usr/bin for security
    cd "/usr/bin"
    command -v "$RUN" >/dev/null || { echo "mx-installer: Command '$RUN' not found"; exit 1; }
    exec "$RUN"
fi

exit
