#!/bin/bash

## bash library for formatusb

##arguments format, label, device

partnum=""

device="$1"
format="$2"
label="$3"
part="$4"

echo device is $device format is $format 
echo label is $label partition work is $part

clearpartions(){
live-usb-maker gui partition-clear --color=off -t "$device"
}

makeusb(){
live-usb-maker gui --format="$format" --color=off -t "$device"
}

labelusb(){


#ensure some partnums when working on devices

if [ "$part" != "part" ]; then
	
	partnum="1"
	
	#if device is mmc, then partnum=p1

	if [[ "mmc" == *"$device"* ]]; then
		partnum="p1"
	fi

	#if device is nvme, then partnum=p1
	if [[ "nvme" == *"$device"* ]]; then
		partnum="p1"
	fi
fi

#ensure device is unmounted
umount /dev/"$device$partnum"

    
case $format in 

	vfat) fatlabel /dev/"$device$partnum" "$label" ;;
	
	ext4)  e2label /dev/"$device$partnum" "$label" ;;
	
	ntfs)  ntfslabel /dev/"$device$partnum" "$label" ;;
	
	exfat) exfatlabel /dev/"$device$partnum" "$label" ;;
	
	*)	echo "unknown format, exiting" ;;

esac
}
partitionrefresh(){

partprobe "/dev/$device"

}

cleanuplog(){
	if [ -e "/var/log/formatusb.log" ]; then
		cp /var/log/formatusb.log /var/log/formatusb.log.old
	fi
	if [ -e "/tmp/formatusb.log" ]; then
		cp /tmp/formatusb.log /var/log/formatusb.log
	fi
}

format_partitions(){
	
	echo "formatting partitions"
	
	#ensure device is unmounted
	umount /dev/"$device"

	case $format in 

	vfat) mkfs.fat -F 32 /dev/"$device" ;;
	
	ext4)  mkfs.ext4 /dev/"$device" ;;
	
	ntfs)  mkfs.ntfs -Q /dev/"$device" ;;
	
	exfat) mkfs.exfat /dev/"$device" ;;
	
	*)	echo "unknown format, exiting" ;;

esac
	
	
}

main(){

echo main launched

if [ "$part" = "part" ]; then
	format_partitions
else
	clearpartions
	sleep 1
	makeusb
	sleep 1
fi
	labelusb
	sleep 1
	partitionrefresh
	cleanuplog
}

main
