#!/bin/bash
# random_play.sh v1.2
#
# This script must be run in a directory where you have write permission.
# This script also requires the getmod.sh script to be present in the current  
# working directory.
# 2 subdirectories will be created:
#
#	downloaded/      All downloaded files will be stored there
#   tmp/             Temporary files
#
# To stop this script gracefully, create a file named 'stop' in the directory where
# this script is running. eg:  # touch stop
#
#
DIR_DOWNLOAD=downloaded
DIR_TMP=tmp		# if you change this, change it in getmod.sh 

mkdir -p $DIR_DOWNLOAD
mkdir -p $DIR_TMP

cleanup()
{
	echo "Cleaning up."
	echo "Killing background download script pid $PID"
	kill $PID
	echo "Bye"
	exit 0;
}

# remove the playfile if we are killed so
# the getmod stops downloading.
trap "cleanup" SIGINT SIGTERM

rm  -f stop
./getmod.sh > /dev/null 2>&1 &
PID=$!

while [ ! -f "stop" ]; do
	# Find newly downloaded files
	oldFile=$newFile
	newFile=`find $DIR_TMP | grep -v "^$DIR_TMP$" | grep -v '$oldFile'`
	echo $newFile

	# move previously downloaded files in $DIR_DOWNLOAD
	if [ -n "$oldFile" ]; then
		mv -f $oldFile $DIR_DOWNLOAD
	fi

	# If no files are availble, wait for download to complete
	if [ -z "`find $DIR_TMP | grep -v "^$DIR_TMP$"`" ]; then
		echo "Waiting for download..."
		while [ -z "`find $DIR_TMP | grep -v "^$DIR_TMP$"`" ]; do
			sleep 1
		done

		# find the new downloaded file
		newFile=`find $DIR_TMP | grep -v "^$DIR_TMP$"`
	fi

	# sanity check
	while [ -n "`pidof wget`" ]; do
		sleep 1
	done

	touch play
	mikmod -X $DIR_TMP/*

done

echo "Stop file found. Bye."
cleanup

