#!/bin/bash
export TEXTDOMAINDIR=/usr/share/locale
export TEXTDOMAIN=runner-gui
MSG01="$(gettext -s "password")"
MSG02="$(gettext -s "Authentication failed")"

get_session_info() {
	local session="$1"
	local varname="$2"
  	local IFS=$'\n'
  	eval declare -Ag $varname
  		for row in $($LOGINCTL show-session "$session"); do
    		key="$(echo "${row}"|cut -d= -f1)"
    		val="$(echo "${row}"|cut -d= -f2-)"
    		eval ${varname}[\"${key}\"]=\"${val}\"
 		done
}

seat="seat0"
LOGINCTL="$(command -v loginctl || command -v systemd-loginctl)"
[ -n "$LOGINCTL" ] || exit 1

if [[ -e $LOGINCTL ]]; then
	active_session="$($LOGINCTL show-seat ${seat} 2> /dev/null |grep ActiveSession|cut -d= -f2 )" 
	if [ -n $active_session ] ; then
		get_session_info $active_session session_info > /dev/null 2>&1
		if [[ ${session_info[Type]} != "x11" ]]; then
			allsessions=$($LOGINCTL show-seat $seat 2> /dev/null | grep Sessions |awk -F= '{print $2}')
			for a in $allsessions ; do
				get_session_info $a session_info 
				if [[ ${session_info[Type]} == "x11" ]]; then
					break
				fi
			done
		fi
	fi
fi

# setup display number
SESSION_DISP="${session_info[Display]}"
[ -n "$SESSION_DISP" ] && DISPLAY="$SESSION_DISP"
[ -z "$DISPLAY" ] || DISPLAY=":0"

# find xauthority file
XAUTH=$(ps -p $(pgrep Xorg) -o cmd |tail -n1 |sed 's#\(.*-auth \)\(/\S*\)\( -.*$\)#\2#')
[ -f "$XAUTH" ] && export XAUTHORITY="$XAUTH"

USER='root'
until [ -z "$1" ] ; do
	case "$1" in
	"-u" | "--user" )	shift ; 
						USER="$1" ;;
	"-c" | "--command" )	shift 
							command="$@"
							break ;;
	*)	command="$@" 
		break ;;
	esac
	shift
done

TMPFILE=/tmp/bashsu$$
trap "rm -f $TMPFILE" EXIT 2 3

# fifo needs here to the file to be readed only once
# fd needs here to remove the TMPFILE as early as possible
mkfifo "$TMPFILE"
exec {D}<> "$TMPFILE"
rm -f $TMPFILE
cat >&${D} << EOF
export XAUTHORITY="$XAUTH"
export DISPLAY="$DISPLAY"
dbus-launch $command
EOF

if [ $(id -u) == 0 ]  ; then
	runuser - "$USER" -c  "bash <&${D} &"
# may be USER have no password 
elif :| su - "$USER" -c "bash <&${D} &" 2>/dev/null; then
    true
else
    echo "$(zenity --password --title "$USER $MSG01" 2>/dev/null)" | \
    (su - "$USER" -c "bash <&${D}"|| notify-send "$MSG02") &

fi

