#!/bin/bash
#
# Copyright 2016 Nio Wiklund
#
# GPLv3: GNU GPL version 3
# <http://gnu.org/licenses/gpl.html>.
#
# This is free software: you are free to change and redistribute it.
# There is NO WARRANTY, to the extent permitted by law.
#-----------------------------------------------------------------------------
# author sudodus alias nio-wiklund at launchpad
#
# date        editor   comment
# 2016-11-13  sudodus  created guidus GUI front end to dus 'do usb stuff'
# 2016-12-29  sudodus  version 12.0.0 - mkusb-dus

version="${0##*/} 12.0.0"

redback="\0033[1;37;41m"
resetvid="\0033[0m"
logoansi="\0033[38;5;0;48;5;148m"
logorgb="'#afd700'"
manager=

starttxt="$logoansi ${0##*/} - Do USB Stuff $resetvid
${0##*/} needs superuser permissions (sudo) for some tasks,
in order to prepare and write to the target, a block device."

errtxt=" ${0##*/} needs zenity to provide a GUI for dus, but it is not found.

$redback Please install zenity! $resetvid"

########################################################################

function p_sudo {

sudostr="live system or temporary superuser permissions"
for i in 1 2 3
do
 sudo -n echo "$sudostr" 2> /dev/null > /dev/null
 if [ $? -ne 0 ]
 then
  if [ "$manager" == "z" ]
  then
   zenity --title "${0##*/} - sudo" \
   --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
   --password 2> /dev/null \
   |sudo -S bash -c "echo $sudostr 2> /dev/null" 2> /dev/null
  fi
 fi
 if [ "$?" == "0" ]
 then
  break
 elif [ $i -eq 3 ]
 then
  return 1
 fi
done
}
########################################################################

# main

########################################################################

which zenity > /dev/null
if [ $? -eq 0 ]
then
 echo -e "$starttxt"
 manager="z"
 p_sudo
 if [ $? -eq 0 ]
 then
  if [ "$1" != "%f" ]
  then
   dus "$@"
  else
   dus
  fi
 else 
  echo -e "$redback Bad password, please try again $resetvid"
 fi
else
 echo -en "$errtxt"
fi
echo -en "$logoansi Press Enter to finish ${0##*/} $resetvid"
read -p ""
