#!/bin/bash
#
# Get song info, osd_cat it
file=/home/display/info
font="-*-terminus-medium-r-*-*-96-*-*-*-*-*-*-*"
#font="xft:Terminus"

while(true); do
	# we have a new file
	# when was it modified?
	modtime=`stat -c %Y $file`;

	while [ "$?" -eq "1" ]; do
		modtime=`stat -c %Y $file`; 
	done;

	# parse the current file, see what's going on
	title=`grep ^title $file | sed -e 's/^title //g'`;
	album=`grep ^album $file | sed -e 's/^album //g'`;
	artist=`grep ^artist $file | sed -e 's/^artist //g'`;
	date=`grep ^date $file | sed -e 's/^date //g'`;
	tracknumber=`grep ^tracknumber $file | sed -e 's/^tracknumber //g'`;
	duration=`grep ^length $file | sed -e 's/^~#length //g'`;

	# maximum line length is 28 characters

	if [ -z "$title" ]; then
		title="Who knows what this is?";
	fi
	if [ -z "$artist" ]; then
		artist="This script has no idea.";
	fi
	if [ -z "$album" ]; then
		album="We should tag music.";
	fi
	if [ -z "$date" ]; then
		date="????";
	fi
	if [ -z "$tracknumber" ]; then
		tracknumber="??/??";
	fi
	
	rm /tmp/.temp;

	if [ "${#title}" -gt "28" ]; then
		char=0;
		while [ "$char" -lt "${#title}" ]; do
			echo "${title:$char:28}" >> /tmp/.temp;
			char=$(($char + 28));
		done;
	else
		echo "$title" > /tmp/.temp;
	fi

	if [ "${#artist}" -gt "28" ]; then
		char=0;
		while [ "$char" -lt "${#title}" ]; do
			echo "${artist:$char:28}" >> /tmp/.temp;
			char=$(($char + 28));
		done;
	else
		echo "$artist" >> /tmp/.temp;
	fi

	if [ "${#album}" -gt "28" ]; then
		char=0;
		while [ "$char" -lt "${#title}" ]; do
			echo "${album:$char:28}" >> /tmp/.temp;
			char=$(($char + 28));
		done;
	else
		echo "$album" >> /tmp/.temp;
	fi

	echo "$tracknumber" >> /tmp/.temp;
	echo "$date" >> /tmp/.temp;

	lines=`cat /tmp/.temp | wc -l`;

	# remove old
	killall osd_cat;

	# we can only assume that this display will be good for up to five seconds
	DISPLAY=:0.0 osd_cat -d 3 -l $lines -p middle -A centre -c yellow -f $font /tmp/.temp &

	# wait until $file is modified
	next=0;
	count=0;
	while [ "$next" -eq "0" ]; do
	     sleep 0.2;
 
	     # make sure the file exists
	     if [ -e $file ]; then
		     newtime=`stat -c %Y $file`;
		     if [ "$newtime" -ne "$modtime" ]; then
	     		next=1;
		     fi;
	     fi;

	     count=$(($count + 1));
	     if [ "$count" -eq "10" ]; then
		DISPLAY=:0.0 osd_cat -d 3 -l $lines -p middle -A centre -c yellow -f $font /tmp/.temp&
		count=0;
	     fi
	done;

	# until the next one comes around
	DISPLAY=:0.0 osd_cat -d 3 -l $lines -p middle -A centre -c yellow -f $font /tmp/.temp&
	
	# file modification may not have finished yet
	sleep 0.5;

	# loop back and do it again
done;
