#!/bin/bash
echo " Timer USB Script...."

while true 
do
	usbdir=
	
	# Check for USB storage device but ignore if pending format request
	if [ -b "/dev/sda" ] && [ ! -f "/tmp/checkusb_format_sda" ]; then
		
		# Create partition table status file if not already
		if [ ! -f "/tmp/sda_fdisk.sts" ]; then
			fdisk -l /dev/sda > /tmp/sda_fdisk.sts
			blkid | grep "/dev/sda" > /tmp/sda_blkid.sts
		fi
		
		# USB device exists so decide what to do with it
		if blkid | grep "/dev/sda1" | grep -q "ext4"; then
			# ext4 partition used for recording
			usbdir=/mnt/recording
		elif blkid | grep "/dev/sda1" | grep -q "vfat"; then
			# fat partition used for upgrades
			usbdir=/mnt/upgrade
		fi

		# If USB partition appears to be useful
		if [ "$usbdir" ]; then
		
			# Check it's not already mounted
			if ! grep -qs $usbdir /proc/mounts; then
				# Mount partition to required folder
				mkdir -p $usbdir
				mount /dev/sda1 $usbdir
			fi
			
			# Update remaing space
			df -h /dev/sda1 > /tmp/sda1_df.tmp
			mv /tmp/sda1_df.tmp /tmp/sda1_df.sts
		fi
	fi
	
	# If USB partition is not useful then clean up
	if [ -z "$usbdir" ]; then
	
		# Remove mounts after uncontrolled removal
		if grep -qs '/mnt/recording ' /proc/mounts; then
			umount /mnt/recording
		fi
		if grep -qs '/mnt/upgrade ' /proc/mounts; then
			umount /mnt/upgrade
		fi
		
		# Remove status files if device removed or is being formatted
		if [ ! -b "/dev/sda" ] || [ -f "/tmp/checkusb_format_sda" ]; then
			rm -f /tmp/sda*.sts		
		fi
	fi	
	
	# Check for pending format request
	if [ -f "/tmp/checkusb_format_sda" ]; then
	
		# Create single large partition on USB device
		if echo ';' | sfdisk /dev/sda > /tmp/sda_sfdisk.out; then
			
			# Format partition ext4 with options best for large files
			mkfs.ext4 -F -T largefile4 -m 0 /dev/sda1 > /tmp/sda1_mkfs.out
		fi
		
		# Remove pending format request
		rm -f /tmp/checkusb_format_sda
	fi
	
	sleep 5 
done
