#!/bin/sh

interval=30 # seconds
logfile=/tmp/itunes_current.log
tmpfile=/tmp/itunes_current

# $1 <outfile>
write_current() {

    lsof -c iTunes|sed -e 's/^.*VREG.*iTunes Music\(.*\)$/Song: \1/ p; s/^.*TCP.*daap->\(.*\):.*$/Connected: \1/ p; /./ d' > "$1"
}

echo "Welcome to Curious Tunes."
echo
echo "This script works by looking for the differences in the list of"
echo "songs that iTunes is currently accessing. As such, it shows both"
echo "the music that *you* are listening to, as well as the music that"
echo "others are listening to. It also shows you any new connections to"
echo "your share, which will let you try and figure out who is listening"
echo "to what."
echo
echo "This script has obvious limitiations, most notably the inability to"
echo "say exactly what song is associated with what remote computer. It is,"
echo "however, better than nothing. Which is what iTunes gives you."
echo
echo "Copyright 2006 Steve Pomeroy http://staticfree.info/"
echo "Released under the GNU GPL. No warranties, etc."
echo 
echo "Refreshing every $interval seconds starting now..."

while test 1; do
	write_current "$tmpfile";
	sleep "$interval";
	if [ -f "$tmpfile.prev" ]; then
		out=`diff "$tmpfile.prev" "$tmpfile"`;
		if [ "$out" != "" ]; then
			date|tee -a "$logfile";
			echo "$out"|grep -E '^>'|tee -a "$logfile";
		fi
	fi
	mv "$tmpfile" "$tmpfile.prev";
done
