#!/bin/bash

# Copy to USB Key Tool Copyright 2009,2011 by Tony Brijeski under the GPL V2
# Using yad for gui calls
#
# Remasterd for SparkyLinux by Paweł "pavroo" Pijanowski <pavroo@onet.eu> 2014/06/05
# Copyright 2014,2015,2016 by Paweł Pijanowski under the GPL V2
# Last update 2016/05/23

# get default's locale file
DEFLOCDIR="/usr/share/pearl/pearl-live-usb-creator"
if [ "`cat /etc/default/locale | grep ar`" != "" ]; then
. $DEFLOCDIR/ar
elif [ "`cat /etc/default/locale | grep de_DE`" != "" ]; then
. $DEFLOCDIR/de
elif [ "`cat /etc/default/locale | grep es_AR`" != "" ]; then
. $DEFLOCDIR/es
elif [ "`cat /etc/default/locale | grep fr_FR`" != "" ]; then
. $DEFLOCDIR/fr
elif [ "`cat /etc/default/locale | grep it_IT`" != "" ]; then
. $DEFLOCDIR/it
elif [ "`cat /etc/default/locale | grep ja_JP`" != "" ]; then
. $DEFLOCDIR/ja
elif [ "`cat /etc/default/locale | grep pl_PL`" != "" ]; then
. $DEFLOCDIR/pl
elif [ "`cat /etc/default/locale | grep pt_BR`" != "" ]; then
. $DEFLOCDIR/pt_BR
elif [ "`cat /etc/default/locale | grep pt_PT`" != "" ]; then
. $DEFLOCDIR/pt_PT
elif [ "`cat /etc/default/locale | grep sv_SE`" != "" ]; then
. $DEFLOCDIR/se
else
. $DEFLOCDIR/en
fi

DIALOG="`which yad` --width 400"
TITLE="--always-print-result --dialog-sep --window-icon=usb-creator --image=usb-creator --title="
TITLETEXT="$LOCAL1"
TEXT="--text="
FILESELECTION="--file-selection "
OKBUTTON="--button=Ok:0 "

testroot="`whoami`"

if [ "$testroot" != "root" ]; then
	/usr/bin/remsu $0 &
fi

copymenu () {
if [ "$1" = "(null)" ]; then
	$DIALOG $TITLE"$TITLETEXT" $TEXT"\n$LOCAL2"
	mainmenu
fi

if [ "$2" = "(null)" ]; then
	$DIALOG $TITLE"$TITLETEXT" $TEXT"\n$LOCAL3"
	mainmenu
fi

$DIALOG $TITLE"$TITLETEXT" $TEXT"\n$LOCAL4"

if [ $? != 0 ]; then
	mainmenu
fi

umount `mount | grep $1 | awk '{print $1}'`

#do the copy
$DIALOG $TITLE"$TITLETEXT" $TEXT"$LOCAL5\n" --no-buttons --progress --pulsate --auto-close --auto-kill &
dd if=$2 of=/dev/$1 bs=4M && sync

killall -KILL yad

$DIALOG $TITLE"$TITLETEXT" $TEXT"\n$LOCAL6" $OKBUTTON

}

mainmenu () {
DEVS=""
DEVS=`ls -l /dev/disk/by-path/*usb* | grep -v "part" | awk '{print $NF}' | awk -F "/" '{print $NF}'`
if [ "$DEVS" != "" ]; then
	for i in $DEVS; do
		USBDRIVESIZE=`grep -m 1 "$i" /proc/partitions | awk '{print $3}'`
		USBDRIVES="$USBDRIVES!$i-$USBDRIVESIZE"
	done
else
	$DIALOG $TITLE"$TITLETEXT" $OKBUTTON $TEXT"\n$LOCAL7"
	exit 0
fi

CHOICES=`$DIALOG $TITLE"$TITLETEXT" --form --field="$LOCAL8:CB" $USBDRIVES --field="$LOCAL9:FL" --button="$LOCAL10:2" --button="$LOCAL11:1"`
retval="$?"

if [ "$retval" = "1" ]; then
	USBDRIVE=`echo $CHOICES | cut -d "|" -f 1 | cut -d "-" -f 1`
	PICKSOURCE=`echo $CHOICES | cut -d "|" -f 2`
	copymenu $USBDRIVE $PICKSOURCE
else
	exit 0
fi
}

mainmenu
