#! /bin/sh


Collect_Numbers()
{
#Generating new audio index
echo "Generating new audio index"

# Clean dbfile
if [ -f audio.db ]
then
	rm -f audio.db
fi

# Clean tempfile
if [ -f audio.tmp ]
then
	rm -f audio.tmp
fi

ls -1 | grep -v "\ " | while read line
   do COUNT=`expr $COUNT + 1`
      #echo "$COUNT ${line}"
      echo "$COUNT ${line}" >> audio.db
   done
}

Match_Number()
{
# Clean tempfile
if [ -f audio.tmp ]
then
	rm -f audio.tmp
fi

# Start while loop
echo "Starting while loop"
while ! [ -f audio.tmp ]
do
	echo "Generating Random number of max 3 chars"
	NUMBER_1=`echo ${RANDOM} | cut -c 2-4`
	#echo "NUMBER_1=${NUMBER_1}"

	#Test NUMBER_2 check
	#NUMBER_1=11

	# Check Random number for min 3 chars
	echo "Checking Random number for min 3 chars"
	NUMBER_2=`echo ${NUMBER_1} | grep ... `
	#echo "NUMBER_2=${NUMBER_2}"
	if ! [ -z ${NUMBER_2} ]
	then
		# Generate Dir from Number
		echo "Generating Dir from Number"
		DIR=`grep ${NUMBER_2} audio.db |awk '{print $2}'`
		echo "NUMBER_2=${NUMBER_2}"
		#echo "DIR=${DIR}"

		if ! [ -z ${DIR} ]
		then
			# Writing Info to tempfile
			echo "Writing Info to tempfile"
			echo ${DIR} > audio.tmp
		fi
	fi
done
}

Mplayer()
{
echo "Entered Mplayer function"
#echo "DIR=${DIR}"
cd ${DIR}

# Check for shuffle play
echo "Checking for shuffle play"
if [ -f shuffle ]
then
	echo "Shuffle play"
	SHUFFLE="-shuffle"
else
	echo "No shuffle play"
	SHUFFLE=""
fi

#Check for playlist and play
echo "Checking for playlist in ${DIR}"
if [ -f playlist ]
then
	echo "Starting to play from playlist"
	echo ""
	for i in `cat playlist`
	do
		mplayer -vo /dev/null -quiet ${SHUFFLE} ${i} ${i}/* ${i}/*/*
	done
else
	echo "Starting to play from directory"
	echo ""
	mplayer -vo /dev/null -quiet ${SHUFFLE} * */* */*/*
fi

# Go back to basedir
cd "$BASEDIR"
}

Check_Time()
{
# Play another one?
HOUR=`date +%H`
echo "HOUR=${HOUR}"
case ${HOUR} in
	06)
	echo "Time is 6 am"
	;;
	07)
	echo "Time is 7 am"
	;;
	08)
	echo "Time is 8 am"
	;;
	09)
	echo "Time is 9 am"
	;;
	10)
	echo "Time is 10 am"
	;;
	11)
	echo "Time is 11 am"
	;;
	*)
	echo "Time is ${HOUR} am/pm"
	echo "Time to get out of bed"
	exit
	;;
esac
}


### Main ###
COUNT="100"
BASEDIR="/mpg/mp3"
echo ""
echo "Starting"
cd "$BASEDIR"
echo "Current dir is: `pwd`"

Collect_Numbers
Match_Number
Mplayer

Check_Time

Match_Number
Mplayer

Check_Time

Match_Number
Mplayer

Check_Time

Match_Number
Mplayer

echo " Back in Main, exiting"
exit

