#!/bin/sh 
#
# mail2sms a shell script
# Matt Foster 
# matt@molnir.demon.co.uk
#
# Mail to SMS gateway script, version 1.0
# By Andy Hawkins (andy@gently.demon.co.uk)


/usr/bin/cp /dev/null /tmp/header.$$
ELINE=0
while [ $ELINE -lt 3 ]
do
  read LINE
  echo "$LINE" >> /tmp/header.$$
  if [ "$LINE" = "" ]
  then
    ELINE=3
  else
    ELINE=0
  fi
done

SENDER=`head -n 1 /tmp/header.$$ | awk '{print $2}'`
TARGET=`grep ^Subject: /tmp/header.$$ | awk '{print $2}'`


ELINE=0
while [ $ELINE -lt 2 ]
do
  read LINE
  echo "$LINE" >> /tmp/body.$$
  if [ "$LINE" = "" ]
  then
    let ELINE=ELINE+1
  else
    ELINE=0
  fi
done



RETRY=5
SENT=0
while [ $RETRY -gt 1 ] && [ $SENT -eq 0 ]
do
  MSG=`cat /tmp/body.$$`
  /usr/bin/sms_client $TARGET "$MSG" >> /tmp/sms.log
  case $? in
   0) /bin/mailx -s "SMS success to $TARGET" $SENDER < /dev/null 
      SENT=1;;
   1) echo "Message too long" | \
           /bin/mailx -s "SMS failure to $TARGET" $SENDER
           SENT=1;;
           
   3) echo "Invalid Service Name" | \
           /bin/mailx -s "SMS failure to $TARGET" $SENDER
      SENT=1;;
   4)
      echo "Unknown number / name $TARGET" | \
           /bin/mailx -s "SMS failure to $TARGET" $SENDER
      SENT=1;;
   *)
      sleep 10
      let RETRY=RETRY-1;;
  esac
done

if [ $SENT -eq 0 ]
then
    echo "Unable to send message after 5 attemps, please try later" | \
        /bin/mailx -s "SMS failure to $TARGET" $SENDER
exit
fi

rm /tmp/header.$$
rm /tmp/body.$$
