#!/bin/bash


echo starting > /var/log/groovix/usb-creator.log

EMSG='\n\nYou may close any file manager windows that pop up\n  as the device partitions and filesystems are deleted and recreated.\n\n'

######################################################################################
#parse command line arguments
until [ -z "$1" ]
do
  CURARG=$1
  case "$CURARG" in
    "--dev="* )        GXHD=${CURARG#*=} ;;
    "--dev"   ) shift; GXHD=$1 ;;
    "--iso="* )        ISOFILE=${CURARG#*=} ;;
    "--iso"   ) shift; ISOFILE=$1 ;;
    "--gui")        MYGUI=1  ;;
    "--help")        MYHELP=1  ;;
  esac
  shift
done
######################################################################################


if [ -n "$MYGUI" ] ; then
	ZENITY=zenity
else
	ZENITY=false
fi

USAGE=" usage: $0 [ --help ] [ --gui ] --iso /tmp/groovix.iso --dev /dev/sdx "
#handle undefined variables
#for booleans, undefined or "" is the only boolean false, test using: if [ $MYFLAG ]
if [ -n "$MYHELP" ] ; then 
	echo $USAGE
	exit 1
fi

if [ -z "$ISOFILE" ] ; then 
	ISOFILE=$($ZENITY --width=550 --height=350 --title="USB Creator - Choose .iso file" --file-selection --file-filter='*.iso')
	if [ $? -ne 0 ] ; then
		echo $USAGE
		exit 1
	fi
fi
if [ -z "$GXHD" ]  ; then 
	#GXHD=$($ZENITY --title="Choose a USB Device"  --file-selection --filename /dev/ --file-filter='sd?')

declare -a ZENLISTARRAY

for MYDEV in $( ls -d /sys/block/sd? | cut -f 4 -d/ ) ; do
        VENDOR=$(cat /sys/block/$MYDEV/device/vendor) ;
        MODEL=$(cat /sys/block/$MYDEV/device/model) ;
        SIZE=$(cat /sys/block/$MYDEV/size);
        SIZEGB=$((SIZE / 1953125 + 1 )) ;
        REMOVEABLE=$(cat /sys/block/$MYDEV/removable)
        if [ $SIZE -gt 0 ] && [ "$REMOVEABLE" = "1" ] ; then
                #echo $MYDEV $VENDOR \"$MODEL\" ${SIZEGB}GB; 
                ZENLISTARRAY=( "${ZENLISTARRAY[@]}" "$MYDEV" "$VENDOR" "$MODEL" "${SIZEGB}GB" )
        fi
done

#echo "${ZENLISTARRAY[@]}"

ZENDEV=$($ZENITY --width=550 --height=350  --list  --title="USB Creator - Choose USB Device" --column=device --column=vendor --column=model --column=size "${ZENLISTARRAY[@]}" )
	if [ $? -ne 0 ] ; then
		echo $USAGE
		exit 1
	fi
GXHD=/dev/$ZENDEV

fi


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

GXHDBASENAME=$(basename $GXHD)

#sanity checks

if [ -f $ISOFILE ]  ; then
	true
else
	echo "iso file $ISOFILE does not exist!"
	exit 1
fi

REMOVEABLE=$(cat /sys/block/$GXHDBASENAME/removable)
#echo "################# $sysblock removeability is $REMOVEABLE #####################"
if [ "$REMOVEABLE" = "1" ] ; then
	echo "$GXHD is classified as removable"
else
	echo specified device $GXHD IS NOT CLASSIFIED AS REMOVABLE!  | tee -a /var/log/groovix/usb-creator.log
	echo WILL NOT CONTINUE
	$ZENITY --width=550 --height=350 --error --title "USB Creator - Failed" --text "see /var/log/groovix/usb-creator.log for details"
	exit 1
fi

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

#ISOSIZE=$(du -k $ISOFILE  | cut -f 1)
ISOSIZE=$(du -b $ISOFILE  | cut -f 1)
#DISKSIZE=$(cat /sys/block/$GXHDBASENAME/size)
DISKSIZE=$(blockdev --getsize64 /dev/$GXHDBASENAME)

if [ $ISOSIZE -ge $DISKSIZE ] ; then
	echo "disk size $DISKSIZE is smaller than iso size $ISOSIZE"
	exit 1
else
	echo "disk size $DISKSIZE is bigger than iso size $ISOSIZE"
fi

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

whoami| grep root
if [ $? -ne 0 ] ; then
	echo "you must run this with root permissions" 
	exit 1
fi

function makedisk {

fdisk -l $GXHD
echo
echo GXHD is $GXHD
echo ISOFILE is $ISOFILE
echo

echo will continue with formatting ${GXHD}1 in 10 seconds
sleep 10

echo "#Reformatting...$EMSG"


GXHDPART=${GXHD}1

sleep 2

umount ${GXHD}*

# if drive had .iso copied to it iso9660 filesystem seems to be able to persist despite reformatting!
wipefs --all $GXHD


                echo parted --script $GXHD print
                parted --script $GXHD print

                # scripted mode doesn't work due to it thinking drive is in use and no Ignore error option
                #parted -- $GXHD mklabel msdos Ignore Yes Ignore quit
                echo parted --script --  $GXHD mklabel msdos
                parted --script --  $GXHD mklabel msdos
                if [ $? -ne 0 ] ; then
                        echo sgdisk --zap $GXHD
                        sgdisk --zap $GXHD
                fi

		#don't need for usb drives?
                #fdisk -l $GXHD 2>&1 | grep "GUID Partition Table"
                #if [ $? -eq 0 ] ; then
                #        echo
                #        echo
                #        echo
                #        echo "####################################################################"
                #        echo "####      ATTENTION: MANUAL INTERVENTION REQUIRED!!!!!!!    ########"
                #        echo "####          \"Ignore\" all errors, answer \"Yes\"!            ########"
                #        echo "####################################################################"
                #        echo
                #
                #        parted -- $GXHD mklabel msdos
                #else
                #        echo "####################################################################"
                #        echo "#######         GPT HAS BEEN ERASED SUCCESFULLY!           #########"
                #        echo "####################################################################"
                #fi

                partprobe $GXHD
                partprobe -s $GXHD
		umount ${GXHD}*

                echo "after erasing GPT: parted --script $GXHD print"
                parted --script $GXHD print


        fdisk $GXHD <<EOF
o
n
p



w
EOF


# toggle part 1 bootable on
		fdisk $GXHD <<EOF
a
1
w
EOF



# partition type
                fdisk $GXHD <<EOF
t
c
w
EOF



        partprobe $GXHD
        partprobe -s $GXHD
	umount ${GXHD}*


# os might try to automount partitions here after they changed, wait a bit and then umount again
sleep 5
	umount ${GXHD}*
sleep 1

echo "#Making Filesystem...$EMSG"
mkdosfs -n 'GROOVIX-USB' -I ${GXHDPART} -F 32


mkdir -p /mnt/groovix-usb-creator-usbmount
umount /mnt/groovix-usb-creator-usbmount 2>/dev/null
mount ${GXHDPART} /mnt/groovix-usb-creator-usbmount

mkdir -p /mnt/groovix-usb-creator-isomount
umount /mnt/groovix-usb-creator-isomount 2>/dev/null
mount -o loop $ISOFILE /mnt/groovix-usb-creator-isomount

echo "#Copying Files... (can take 3 to 30 minutes depending on device speed)$EMSG"
rsync -a /mnt/groovix-usb-creator-isomount/ /mnt/groovix-usb-creator-usbmount/

umount /mnt/groovix-usb-creator-isomount
umount ${GXHDPART}

echo "#Installing syslinux...$EMSG"

# -s is "slow and stupid - takes like another 10 seconds to get off the menu screen, do we really need it?"
# zbox was having problems that -s seemed to fix
syslinux -s ${GXHDPART}
#syslinux ${GXHDPART}

mount ${GXHDPART} /mnt/groovix-usb-creator-usbmount

mv /mnt/groovix-usb-creator-usbmount/isolinux /mnt/groovix-usb-creator-usbmount/syslinux
mv /mnt/groovix-usb-creator-usbmount/syslinux/isolinux.cfg /mnt/groovix-usb-creator-usbmount/syslinux/syslinux.cfg

umount ${GXHDPART}

echo "#Writing MBR...$EMSG"

dd bs=446 count=1 conv=sync if=/usr/lib/syslinux/mbr/mbr.bin of=$GXHD

sync

}

if [ -n "$MYGUI" ] ; then
	makedisk | tee -a /var/log/groovix/usb-creator.log | $ZENITY --width=550 --height=350 --title "USB Creator - Writing $ISOFILE to USB Device $GXHD" --progress --pulsate --auto-close --no-cancel --text="Please Wait...$EMSG"
else
	makedisk   | tee -a /var/log/groovix/usb-creator.log
fi

echo "bootable usb creation done"
$ZENITY --width=550 --height=350 --info --title "USB Creator - Done" --text "Bootable USB Device is Ready,\nlog is in /var/log/groovix/usb-creator.log"

true



