#!/bin/bash

user=$(whoami)
if [ "$user" != "root" ]; then
    wunwa "Event Tester" > /dev/null && wmctrl -r 'Event Tester' -N "Root: $(gettext "Super_L key")" &
    kp=$(timeout 2s xev -geometry 260x50 | grep -A2 --line-buffered '^KeyRelease' | sed -n '/keycode /s/^.*keycode \([0-9]*\).* (.*, \(.*\)).*$/\1 \2/p')
sl="Super_L"
else
    sl="unset"
fi

if [[ -z "$@" ]]; then
    bash -c 'wunwa Application > /dev/null; orient-act-win 2' &

    if [[ "${kp}" =~ "$sl" ]]; then
	gsu open-with -p &
    else
	open-with -p &
    fi
else
    h_file="$HOME/.config/x-scheme-handlers"
    handlers="$(cat $h_file)"
    hdl=""; for h in $handlers; do hdl="$hdl"\|$(echo "$h" | cut -d/ -f2 | cut -d= -f1)://; done
    hdl="${hdl/mailto:\/\//mailto:}"
    hdl="^(${hdl:1})"
    if [ -n "$(which ${@%% *})" ]; then
	cmd=eval\ "$@"
    elif [ -e "$@" ]; then
	cmd=eval\ "cd \"$(dirname "$@")\"; all-open \"$(basename "$@")\""
    elif [[ "$@" =~ $hdl ]]; then
	cmd="all-open $@"
    else
	cmd=eval\ "bash -c '$@'"
    fi
    if [[ "${kp}" =~ "$sl" ]]; then
	gsu $cmd &
    else
	msg="$($cmd 2>&1 &)"
	[ -n "$msg" ] && [[ ! "$msg" =~ $(cat $HOME/.config/gtk-3.0/suppress-err-msg | tr ' ' '|') ]]  && yad --fixed --title=$"Error" --window-icon="$HOME/.icons/run.png" --image="dialog-warning" --text='\n\t'"$msg"'\n' --borders=20 --button="OK":0
    fi
fi

