#!/bin/sh
# Start/stop the USB dock and mount/unmount the inserted drives
# starting or stopping the RAID system as needed
#
# poc@usb.ve - 11/06/2020

RAID=/dev/md127
SCAN=/sys/class/scsi_host/host6/scan

LOG=/var/log/dock.log

function raidon() {	# RAID drive is running
	if mdadm --query $RAID > /dev/null 2>&1 ; then
		return 0
	fi
	return 1
}

function mounted() {	# Drive is mounted
	if findmnt /raid > /dev/null 2>&1 ; then
		return 0
	fi
	return 1
}

case $# in
	0) if raidon; then
		if mounted ; then
			echo dock is up and mounted
		else
			echo dock is up and unmounted
		fi
	   else
		echo dock is down
	   fi
	   ;;

	1) case $1 in
		down)	if mounted ; then
				umount /raid > /dev/null 2>&1 
				mounted && exit 1	# Drive is busy
			fi
			mdadm --stop $RAID > /dev/null 2>&1
			echo 1 > /sys/block/sdd/device/delete	# TODO: use udisksctl for this
			echo 1 > /sys/block/sde/device/delete	# 
			(echo -n "down: "; date) >> $LOG
			;;

		up)     mounted && exit 0
			echo "- - -" > $SCAN
			echo -n "raid attempt: " >> $LOG
			for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do	# Wait up to 30 seconds
				sleep 2
				echo -n $i " " >> $LOG
				raidon && break
			done
			raidon || (echo -n " failed:"; date; exit 2)		# RAID timed out
			(echo; echo -n "up:   "; date) >> $LOG
			mount /raid > /dev/null 2>&1
			mounted || (echo "mount failed"; exit 3)		# Mount failed
			;;

		*)	echo "dock [up|down]"
	    esac
	    ;;

	*) echo "dock [up|down]"
esac
