#!/bin/sh

 curl="/usr/bin/curl -s"
inurl="http://www.twitter.com/statuses/mentions.xml"
   pw='REDACTED!'
 temp="/tmp/$(basename $0).$$"

lastidcache="/Users/dave/Documents/Linux Journal/.last-tweet-id"

tweet="./tweet.sh"

trap "/bin/rm -f $temp" 0 1 9 15	# axe our temp file

$curl -u "davetaylor:$pw" $inurl | \
  grep -E '(<screen_name>|<text>|<id>)' | \
  sed 's/@DaveTaylor //;s/  <text>//;s/<\/text>//' | \
  sed 's/ *<screen_name>//;s/<\/screen_name>//' | \
  sed 's/ *<id>//;s/<\/id>//' | \
  awk '{ if (NR % 4 == 0) { printf ("name=%s; ", $0) } else if (NR % 4 == 1) { printf ("id=%s; ",$0) } else if (NR % 4 == 2) { print "msg=\"" $0 "\"" } }' > $temp

# manage our last ID tracking system

latestid=""	# latest of the current batch
answered=0	# haven't answered any yet

if [ -f "$lastidcache" ] ; then
  previouslatestid="$(cat "$lastidcache")"
else 
  previouslatestid="0"
fi

while read buffer
do
  eval $buffer
  # strip out the &quot; sequences, etc, along with punctuation
  msg="$(echo $msg | sed 's/\&quot;//g' | tr -cd ' [:alpha:]')"

  if [ -z "$latestid" ] ; then
    latestid=$id	# store most recent ID
  fi

  if [ "$id" == "$previouslatestid" -o $answered -eq 1 ] ; then
    echo "already answered query \"$msg\" from $name: skipped"
    answered=1
  else
    if [ "$msg" == "hours" ] ; then
      echo "Twitter user @$name asked what our hours are in tweet $id"
      $tweet "@$name our hours are Mon-Fri 9-5, Sat 10-4. Thanks for asking!"
    elif [ "$msg" == "time" ] ; then
      echo "Twitter user @$name asked for the time"
      $tweet @$name the local time on our server is $(date)
    elif [ "$msg" == "directions" ] ; then 
      echo "Twitter user @$name asked for directions in tweet $id"
      $tweet "@$name directions to our office are here: SOMEURL"
    elif [ "$msg" == "address" ] ; then 
      echo "Twitter user @$name asked what our address in tweet $id"
      $tweet "@$name we're located at 123 University Avenue, Anywhere USA"
    else
      echo "ignoring $msg: don't know what $name is asking."
    fi
  fi
done < $temp

# now let's store the most recent ID for the next invocation

echo $latestid > "$lastidcache"

exit 0

