#! /bin/sh

sincefile=~/.twatch.since
name=$(basename $0)

tmpfile=`mktemp -q /tmp/${name}.XXXXXX`
if [ $? -ne 0 ]; then
	echo "$name: Can't create temp file, exiting..."
	exit 1
fi

if [ ! -f ~/.twatch.rc ]; then
	echo "$name: I need a ~/.twatch.rc file."
	exit 1
fi

. ~/.twatch.rc

prowl_send()
{
	/usr/local/bin/prowl.pl -apikeyfile=$HOME/.prowl \
		-application="Twitter" \
		-event="$1" \
		-notification="$2" \
		-priority=0 >/dev/null 2>&1
}

since=$(cat $sincefile 2>/dev/null)

if [ -n "$since" ]; then
	since="&since_id=$since"
fi

/usr/local/bin/curl -s -o $tmpfile "http://search.twitter.com/search.atom?q=@${login}${since}"

last=$(grep '^    <id>' $tmpfile | head -1 | sed 's|.*:\([0-9]*\).*|\1|')

if [ -n "$last" ]; then
	echo $last > $sincefile
fi

count=0
cat $tmpfile | while read line; do
	case $line in
		*'<title>'*)
			title=$(echo $line | sed 's|.*<title>||;s|</title>.*||')
			;;
		*'<name>'*)
			name=$(echo $line | sed 's|.*<name>||;s| .*||')
			count=$(($count + 1))
			if [ $count -le 3 ]; then
				sleep 5
				prowl_send Mention "@$name: $title"
			fi
			;;
		*)
			;;
	esac
done

rm $tmpfile

