#!/bin/bash

Info () {
title="Info"
author="Peter Starfinger"
mail="E-Mail: info@die-starfingers.de"
year="2020"
app="$(basename $0)"
msgid="The Starbuntu application
<i>\$app</i>
was written by"
info="$(gettext "$msgid" | (export PATH `envsubst --variables "$msgid"`; envsubst "$msgid"))"

yad --center --fixed --title="$title" --window-icon="/usr/share/icons/gnome/48x48/status/info.png" --image="/usr/share/icons/gnome/48x48/status/info.png" --borders=20 --text="$info"$'\n'$'\n'"$author"$'\n'"$mail"$'\n'$'\n'"$year"$'\n' --text-align=center --selectable-labels --button="OK" &
wunwa "$title" > /dev/null; xdotool key Home key Down
}

[ "$1" = "info" ] && Info && exit 0
device="$@"
[[ "${device::1}" =~ 1|2 ]] && wins=${device::1} && device="${device:2}" || wins=1

user=$(whoami)
own="$(lsblk -o KNAME,TYPE,TRAN | grep disk | grep -v usb | cut -d\  -f1)"

if [ -z "$device" ]; then
  $(sudoer $user) && nono="ß" || nono="$own"
  IFS=$'\n'
  partprobe
  dev=($(lsblk -o KNAME,LABEL,TYPE,FSTYPE,MOUNTPOINTS | grep -E "part"\|"rom" | grep -v $nono | grep -v /$ | grep -v "swap"))
  for d in ${dev[@]}; do d=${d% part*}; d=${d% rom*}; d=${d// / }; dev_=(${dev_[@]} $'\t\t'/dev/$d); done
  n=${#dev_[@]}; height=$((n*30+100))
  text=$"Which block device shall be opened?&#10;"
  title=$"Block Devices"
  cancel=$"Cancel"
  device=$(yad --center --title="$title" --window-icon="$HOME/.icons/usb-stick.png" --text="<b>$text</b>" --text-align="center" --width=440 --height=$height --borders=20 --list --no-headers --column=Device ${dev_[@]} --button="$cancel":1 --button="Info":"$0 info" --button="OK":0)
  button=$?
  device="${device:2}"; device=${device%% *}
else
  button=0
  [[ ! "$device" =~ "/dev/" ]] && device="/dev/$device"
  ! $(sudoer $user) && [[ "$device" =~ "$own" ]] && exit 0
fi

if [ $button -eq 0 ]; then
  #  cd /media/$(whoami)
  udcreply=$(udisksctl mount -b $device 2>&1)
  [[ $udcreply =~ "\`" ]] && mounted="$(echo "$udcreply" | cut -d\` -f2 | cut -d\' -f1)" || mounted="$(echo  "$udcreply" | cut -d\  -f4)"
  
  if [ $wins -eq 1 ]; then
    Rox $mounted
    until [[ "$(wmctrl -l)" =~ "$mounted" ]]; do :; done
    while [[ "$(wmctrl -l)" =~ "$mounted" ]]; do sleep 1; done
  else
    sh -c 'wunwa "Xephyr" > /dev/null; orient-act-win 8' & Rox2 1024x640 "$(basename $mounted) " $mounted $HOME
  fi

  udcreply=$(2>&1 udisksctl unmount -bf $device)
  text=$"Now the mass storage
may be removed!"
  if [[ $udcreply =~ "Unmounted" ]] && [[ ! $device =~ "$own" ]]; then
    notify-send -i info "$text"
  fi
fi

