#!/bin/bash

filers () {
  HOME="/$(whoami)"
  [ "$HOME" != '/root' ] && HOME="/home$HOME"
  socket="$(find /tmp/.X11-unix | sort | tail -1)"
  Rox $param3 2> /dev/null & wunwa "$wmctrl_param3" > /dev/null; orient-act-win s4
  ROX-Filer $param4 2> /dev/null & wunwa "$wmctrl_param4" > /dev/null; orient-act-win s6
  while [ -S "$socket" ]; do sleep 1; done
}

param1="$1"; param2="$2"; param3="$3"; param4="$4"

dpls=($(ls /tmp/.X11-unix))
n_dpls=${#dpls[@]}

if [ "$param2" = "filers" ]; then
  filers
  sed -i "s/Sans ../Sans 11/" $HOME/.gtkrc-2.0
  exit 0
fi

if [ ! -d "$param1" ] && [ -d "$param2" ]; then
  param4="$param3"
  param3="$param2"
  param2=""
fi

if [ -d "$param1" ]; then
  param3="$param1"
  param4="$param2"
  param1=""
  param2=""
fi

if [ -z "$param1" ]; then
  param1="1024x640"
fi

if [ -z "${param2// /}" ]; then
    param2="$(basename "$param3")        $(basename "$param4")"
    [ -z "${param2// /}" ] && param2="Rox2"
fi

xkblayout=$(setxkbmap -query | grep layout)
xkblayout="${xkblayout: -2}"
sh -c 'xseticon -id `wunwa Xephyr` ~/.icons/rox2.png' &
unset XDG_SEAT
Xephyr -ac -screen $param1 -resizeable -reset :$n_dpls &
until [ -S "/tmp/.X11-unix/X$n_dpls" ]; do :; done

DISPLAY=:0 xsel -op | DISPLAY=:$n_dpls xsel -ip
DISPLAY=:0 xsel -ob | DISPLAY=:$n_dpls xsel -ib
DISPLAY=:$n_dpls
openbox > /dev/null &
xbindkeys &
setxkbmap -layout $xkblayout
DISPLAY=:0 wmctrl -r "Xephyr on :$n_dpls.0" -N "$param2"
DISPLAY=:$((n_dpls-1)) wmctrl -r "Xephyr on :$n_dpls.0" -N "$param2"

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

[ ${#param3} -gt 1 ] && [ "${param3: -1}" = "/" ] && param3="${param3::-1}"
[ ${#param4} -gt 1 ] && [ "${param4: -1}" = "/" ] && param4="${param4::-1}"
[[ "$param3" =~ ^$HOME ]] && wmctrl_param3="${param3/$HOME/'~'}" || wmctrl_param3="$param3"
[[ "$param4" =~ ^$HOME ]] && wmctrl_param4="${param4/$HOME/'~'}" || wmctrl_param4="$param4"

if $root; then
  if [ -z "$param3" ]; then 
    param3="/"
  fi
  if [ -z "$param4" ]; then
    param4="/"
  fi
  [ $user != "root" ] && gsu "$0 "$param1" filers "$param3" "$param4"" || filers
else
  if [ -z "$param3" ]; then 
    param3="/"
  fi
  if [ -z "$param4" ]; then
    param4="$HOME"
  fi
  filers
fi
sed -i "s/Sans ../Sans 11/" $HOME/.gtkrc-2.0

exit 0
