#!/bin/bash

##
# Post SMS message to Twitter.
#
# Can be used as an Eventhandler for SMS Server Tools 
# <http://smstools.meinemullemaus.de/>
# If used as an Eventhandler the arguments are "RECEIVED" 
# and the path to the SMS file.
# add "eventhandler=/path/to/sms2twitter.sh" to your smsd.conf.
#
# Without SMS Server Tools you can also use a simple file for posting to twitter:
# Create a file starting with "Phone: 0634567890", an empty line and you message
# Then call this script with the path to your file.
#
# You will need to create a sqlite3 DB with this schema:
# sqlite3 sms2twitter.db "CREATE TABLE account (phone, username, password, PRIMARY KEY(phone))"
#
# For every Phone that you allow to post Tweets thru SMS:
# sqlite3 sms2twitter.db "INSERT INTO account VALUES ('phonenumber', 'username', 'password')"
# 
#
# @author Mark Lindeman <mark@lindeman.nu>
##

DB="sms2twitter.db"
CURL=`which curl`
SQLITE3=`which sqlite3`
FORMAIL=`which formail`
UPDATE_URL="http://api.twitter.com/1/statuses/update.json"

test -f "$DB" || {
	echo "DB $DB not found" 1>&2
	exit 1
}

if [[ -z $CURL ]] 
then
	echo "CURL not found" 1>&2
	exit 1
fi

if [[ -z $SQLITE3 ]] 
then
	echo "SQLITE3 not found" 1>&2
	exit 1
fi

if [[ -z $FORMAIL ]] 
then
	echo "FORMAIL (part of procmail) not found" 1>&2
	exit 1
fi

usage()
{
	echo "usage: $0 [RECEIVED] <SMSFILE>"
}

test -z "$1" && {
	usage
	exit 1
}

#if used as a direct Eventhandler then we need to test for the 1st argument:
if [ $# -gt 1 ]
then
	STATUS=$1
	if [ "$STATUS" != "RECEIVED" ]
	then
		echo "expected RECEIVED status" 1>&2
		exit 2
	fi
	shift
fi

SMS=$1

test -f "$SMS" || {
	echo "SMS file not found" 1>&2
	exit 1
}

PHONE=$(formail -zx From: < $SMS)

test -z "$PHONE" && {
	echo "Failed to extract Phonenumber from SMS" 1>&2
	exit 1
}

#search database for phone:
ROW=$($SQLITE3 $DB 'SELECT username, password FROM account WHERE phone="'$PHONE'"')
test -z "$ROW" && {
	echo "no account for phone $PHONE" 1>&2
	exit 2
	
}

USERNAME=$(echo "$ROW"|cut -d'|' -f 1)
PASSWORD=$(echo "$ROW"|cut -d'|' -f 2)

if [[ -z $USERNAME ]] || [[ -z $PASSWORD ]]
then
	echo "invalid credentials for phone $PHONE" 1>&2
	exit 3
fi

#get message from SMS:
MSG=$(formail -I "" <$SMS | sed -e"1d")

if [ ${#MSG} -gt 140 ]
then
	echo "tweets can only be 140 characters long" 1>&2
	exit 3
fi

if [ ${#MSG} -eq 0 ]
then
	echo "empty tweet" 1>&2
	exit 3
fi

ERROR=$($CURL -s -S \
	-H "X-Twitter-Client: PDP SMS Gateway" \
	-H "X-Twitter-Client-Version: 1.0" \
	-H "X-Twitter-Client-URL: http://www.pictura-dp.nl/twitterclient.xml" \
	-u "$USERNAME:$PASSWORD" \
	-d "status=$MSG" \
	$UPDATE_URL \
		| grep '"error"' \
		| sed 's/.\+"error":"\(.\+\)".*}/\1/'

)

if [ ! -z "$ERROR" ]
then
	echo $ERROR 1>&2
	exit 4
fi

exit 0

