#!/bin/bash

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

function usage {

 echo "Run with superuser privileges, as root or with sudo"
 echo ""
 echo "# $0 i       # install as root"
 echo "$ sudo $0 i  # install with sudo"
 echo ""
 echo "# $0 r       # remove as root"
 echo "$ sudo $0 r  # remove with sudo"
}
########################################################################

function dus-remover {

rm -v "$2"/"$1"
}
########################################################################

# main

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

uid=$(whoami)

if [ "$uid" != "root" ] || [ $# -ne 1 ] || ! ( [ "$1" == "i" ] || [ "$1" == "r" ] )
then
 usage
 exit
fi

if [ "$1" == "i" ]
then
 action=install
 tool="cp -v"
elif [ "$1" == "r" ]
then
 action=remove
 tool=dus-remover
fi

read -p "Do you want to $action 'dus' with the graphical user interface 'guidus'? (y/N) " ans
if [ "$ans" != "y" ]
then
 exit
fi

echo "${action} dus ..."

if [ "$action" == "install" ]
then
 mkdir -p /usr/share/applications
 mkdir -p /usr/share/icons/hicolor/scalable/apps
 mkdir -p /usr/share/icons/hicolor/48x48/apps
 mkdir -p /usr/share/mkusb
fi

$tool guidus /usr/bin
$tool guidus.desktop /usr/share/applications
$tool dus /usr/bin
$tool dus-home-backup /usr/bin
$tool dus-home-restore /usr/bin
$tool mkusb-backup-n-restore-home /usr/bin
$tool dus-iso2usb /usr/sbin
$tool dus-live /usr/sbin
$tool dus-persistent /usr/sbin
$tool dus-restore /usr/sbin
$tool dus-wipe /usr/sbin
$tool watch-flush /usr/bin
$tool mkusb-tow /usr/sbin
$tool mkusb-common /usr/bin
#$tool usb-pack-efi /usr/bin
$tool mkusb.svg /usr/share/icons/hicolor/scalable/apps
$tool mkusb.svg /usr/share/icons
$tool mkusb.png /usr/share/icons/hicolor/48x48/apps
$tool dus.8.gz /usr/share/man/man8

if [ "$action" == "install" ]
then
 test -f /usr/share/mkusb && rm /usr/share/mkusb
 $tool mkusb_sdir/* /usr/share/mkusb
# $tool usb-pack_sdir/* /usr/share/mkusb
 ln -v /usr/bin/guidus /usr/bin/mkusb-dus
 ln -v /usr/share/applications/guidus.desktop /usr/share/applications/mkusb-dus.desktop
 sed -i 's/guidus/mkusb-dus/g' /usr/share/applications/mkusb-dus.desktop
 ln -v /usr/share/man/man8/dus.8.gz /usr/share/man/man8/mkusb-dus.8.gz
elif [ "$action" == "remove" ]
then
 rm -rv /usr/share/mkusb
 rm -v /usr/bin/mkusb-dus
 rm -v /usr/share/applications/mkusb-dus.desktop
 rm -v /usr/share/man/man8/mkusb-dus.8.gz
fi

needed="pv parted gdisk lsblk df mount gzip xz xterm rsync tar dialog zenity"

if [ "$action" == "install" ]
then
 for i in $needed
 do
  which "$i" >/dev/null
  if [ $? -ne 0 ]
  then
   if [ "$i" == "lsblk" ]
   then
    echo "please install: util-linux"
   elif [ "$i" == "df" ]
   then
    echo "please install: coreutils"
   elif [ "$i" == "xz" ]
   then
    echo "please install: xz-utils"
   else
    echo "please install: $i"
   fi
  fi
 done
fi
