#!/bin/bash
echo " Timer USB Script...."
renice -n 15 $$

while true 
do
	usbdir=
	format=
	
	# Check whether format has been requested
	if [ -f "/tmp/checkusb_format_sda" ]; then
		format=sda
	fi
	
	# Check for USB storage device but ignore if pending format request
	if [ -b "/dev/sda" ] && [ -z "$format" ]; then
		
		# Create partition table status file if not already
		if [ ! -f "/tmp/sda_fdisk.sts" ] || [ ! -f "/tmp/sda_blkid.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 cat /tmp/sda_blkid.sts | grep "/dev/sda1" | grep -q "vfat"; then
			# vfat partition used for upgrades/recording
			usbdir=/mnt/share/usb
		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
				if mount -t vfat /dev/sda1 $usbdir; then
					mkdir -p $usbdir/b110
				fi
			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 status files if device removed or is being formatted
		if [ ! -b "/dev/sda" ] || [ -n "$format" ]; then
			rm -f /tmp/sda*.sts		
		fi
		
		# Remove mounts after uncontrolled removal
		if grep -qs '/mnt/share/usb ' /proc/mounts; then
	
			# Kill processes using USB device before formatting
			killall recorder

			# Unmount USB storage
			umount /mnt/share/usb

			# Force restart of recorder which might have been killed
			echo 9 > "/tmp/wui_actions"
		fi
	fi	
	
	# Check for pending format request
	if [ -n "$format" ]; then
	
		# Create single W95 FAT32 partition on USB device
		# fdisk input via printf...
		#   o = clear the in memory partition table
		#   n = new partition
		#   p = primary partition
		#   1 = partition number 1
		#     = default - start at beginning of disk 
		#     = default - extend partition to end of disk
		#   t = change partition type
		#   b = partition type W95 FAT32 
		#   w = write the partition table
		#   q = and we're done
		if printf 'o\nn\np\n1\n\n\nt\nb\nw\nq\n' | fdisk /dev/sda > /tmp/sda_fdisk.out; then
			
			# Format partition FAT32
			mkfs.vfat -F 32 /dev/sda1 > /tmp/sda1_mkfs.out
			
		fi
		
		# Remove pending format request
		rm -f /tmp/checkusb_format_sda
	fi
	
	sleep 5 
done
