#!/bin/sh
#

FD="/dev/sda"
FLOPPY="/media/floppy"
MAINPY="${FLOPPY}/main.py"
PYRUN="python ${MAINPY}"
MAINPD="${FLOPPY}/main.pd"
PDRUN="pd -lib import -path /usr/local/lib/pd-externals/net/ -path /usr/local/lib/pd-externals/osc/ -path /usr/lib/pd/extra/cyclone -lib osc -lib udpreceive -oss -r 48000 -rt -nogui ${MAINPD}"

stdbuf -oL -- udevadm monitor --udev -p ${FD} | while read -r -- STATE _ _ _ _
do
	if [ "${STATE}" = "DISK_MEDIA_CHANGE=1" ]
	then
		echo "change detected"
		if [ "$(udisksctl info -b ${FD} | grep filesystem)" ]
		then
			echo "floppy in (fs detected)"
			udisksctl mount -b ${FD} --no-user-interaction
			if [ -e "${MAINPY}" ]
			then
				echo "main.py found"
				$(${PYRUN})&
			fi
			if [ -e "${MAINPD}" ]
			then
				echo "main.pd found"
				$(${PDRUN})&
			fi
		else
			echo "floppy out (no fs detected)"
			if [ "$(pgrep -f '^python')" ]
			then
				echo "python still running ... killing"
				pkill -9 python
			fi
			if [ "$(pgrep -f '^pd')" ]
			then
				echo "pd still running ... killing"
				pkill -9 pd
			fi
 			if [ "$(pgrep -f '^mpv')" ]
			then
				echo "mpv still running ... killing"
				pkill -9 mpv
			fi
		fi
	fi
done


