#!/bin/bash

function print_usage() {
	echo "udisk [ mount | unmount | remount | reformat ]"
}

function get_confirmation() {
	read -r -p "[?] Are you sure you want to reformat udisk? All files will be removed [y/N] " confirm
	case "$confirm" in
	    [yY][eE][sS]|[yY])
	        return 0
	        ;;
	    *)
	        return 1
	        ;;
	esac
}

function mount_udisk() {
	mount -o sync /dev/nandf /root/udisk &> /dev/null
	return $?
}

function unmount_udisk() {
	[[ $(mount | grep /dev/nandf) == "" ]] || {
		sync
		umount /dev/nandf &> /dev/null
		return $?
	}
	return 0
}

function reformat_udisk() {
	dd if=/dev/zero of=/dev/nandf  bs=512  count=1 &> /dev/null
	mkfs.vfat -n "BashBunny" /dev/nandf &> /dev/null
}

function copy_files() {
	mkdir -p /root/udisk/loot
	mkdir -p /root/udisk/tools
	cp /root/version.txt  /root/udisk
	cp -rf /usr/local/bunny/udisk/* /root/udisk/ &> /dev/null
}

function do_format() {
	unmount_udisk && {
		reformat_udisk
		mount_udisk && copy_files
		echo "[*] Udisk formatted successfully. The system will now reboot."
	} || {
		echo "[!] Error: Udisk is busy"
	}
}

case $1 in
	"mount")
		mount_udisk && echo "[*] Udisk mounted to /root/udisk" || echo "[!] Error: Udisk could not be mounted"
		;;
	"unmount" | "umount")
		unmount_udisk && echo "[*] Udisk unmounted" || echo "[!] Error: Udisk is busy, could not unmount"
		;;
	"remount")
		unmount_udisk && (mount_udisk && echo "[*] Udisk re-mounted to /root/udisk") || {
			echo "[!] Error: Udisk is busy, could not unmount"
		}
		;;
	"reformat")
		get_confirmation && do_format && reboot
		;;
	*)
		print_usage
		;;
esac