#!/bin/sh
# send SMS via web
# (C) M. Andreoli 2000

#set -x


#
# configuration
#

server=free.kataweb.it
url="/freesms/freesms_send.html"
ref="www.kataweb.it"

if [ "`which rgrep 2>/dev/null`" ] ; then
	GREP=rgrep
else
	GREP=grep
fi


# 
# send the SMS  
#

send()
{
echo "Sending SMS to $prefix-$destination ..."
msg=`echo -n $message| tr ' ' '+'`
POST="prefix=$prefix&destination=$destination&message=$msg&ref=http%3A%2F%2F${ref}%2F"

len=`echo $POST | wc -c`

cat  <<END  | nc $server 80 
POST $url HTTP/1.0
Host: $server 
Accept: text/html, text/plain
Accept-Language: en
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Bubba/Scaz0.1 
Referer: file://localhost/root/web/freesms_preview.html
Content-type: application/x-www-form-urlencoded
Content-length: $len 

$POST
END
}

check()
{
result=`sed -n /freesms_ok.html/P`
[ -s "$result" ] && return 1
return 0 
}

help()
{
cat <<END
sms, Send SMS messages via Web - (C) 2000 M.Andreoli
Usage:
	# sms xxxx-yyyyyyy [message]
	# sms nickname [message]

If no message specified, read message from standard input. 
Nicknames are in the file /etc/sms.conf, with the syntax:

		nick	phone
		nick 	phone
		....
Without parameters, the script enter in interactive mode.
 
END
exit
}

split_phone()
{
save=$IFS; IFS="-"
set -- $1; prefix=$1; destination=$2
IFS=$save

if [ -z "$prefix" ] || [ -x "$destination" ] ; then
	echo "Error in phone number."
	exit 1
fi

}

#
# Main
#

# parse parameters

[ "Z$1" = "Z-h"  ] && help 

dest=$1;
if [ -z "$dest" ] ; then

	if [ -f /etc/sms.conf ] ; then
	echo "Nicknames:"
	echo "======================================="
	cat /etc/sms.conf
	echo "======================================="
	fi

echo -n "Enter phone-number xxxx-yyyyyy (or nickname): "
read dest

fi


shift 2>/dev/null
if [ $# -ne 0 ] ; then
	message="$*"
else
	echo "Please, input messaged then end with Control-D"
	message=`cat`
fi

# resolv destination 

case $dest in
*-*)
	split_phone $dest 
	;;
*)
	# get nickname	
	[ ! -f /etc/sms.conf ] && echo "Error: Missing nicknames /etc/sms.conf" && exit 1
	export Done=
	entry=`cat /etc/sms.conf | sed -n /$dest/P`
	[ -z "$entry" ] && echo "Error: nickname [$dest] unknown" && exit 1 
	set -- $entry
	phone=$2
	split_phone $phone 
	;;
esac


# ok, send!

send | check
if [ $? -eq 0 ] ; then
	echo "Done."
else
	echo "Fail."
fi

# End
