#!/bin/bash
#
# Shell program to send a text message (SMS) to a given recipient
# via gulesider.no using wget.
#
# Copyright 2010, Richard Tingstad <richard.tingstad+sms@gmail.com>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# See <http://www.gnu.org/licenses/>.
#
# Version 0.03
#
# The following three values must be set:
sender=98765432 #Your phone number.
username='yourEmailAddress'
password='yourPassword'

fil='smsnums.txt'
if [ $# -lt 1 ]
then
 echo "Send SMS with Gulesider.no, by Richard H. Tingstad"
 echo ""
 echo "Usage:   $0 recipient message"
 echo "Example: $0 98765432 Hi! I have emailed you the results you asked for."
 echo ""
 echo "If no message is given as parameter, it is read from stdin."
 echo ""
 echo "You can also store recipients in $fil, one per line, like: nick,98765432"
 echo "You can then $0 nick text."
 exit 1
fi
to=$1
if echo $to|egrep -qi '[a-z]'
then
 if [ -f $fil ]
 then
  if egrep -q $to $fil
  then
   to=`egrep $to $fil|cut -d ',' -f2`
  else
   echo "Recipient $to not found in $fil." >&2
   exit 1
  fi
 else
  echo "File $fil not found." >&2
  exit 1
 fi
fi
msg=""
if [ $# -gt 1 ]
then
 c=0
 for i in $*
 do
 if [ $c -gt 0 ]
  then
   msg="$msg $i"
  fi
  c=$[ $c + 1 ]
 done
else
 while read i
 do
  msg="$msg $i"
 done
fi
if [ ${#msg} -gt 160 ]
then
 delay=5
 echo "Warning: Message is longer than 160 characters (${#msg}). Sending in $delay seconds."
 sleep $delay
fi
msg=`echo "$msg" | sed 's/%/%25/g;s/#/%23/g;s/&/%26/g;s/Æ/%C6/g;s/æ/%E6/g;s/Ø/%D8/g;s/ø/%F8/g;s/Å/%C5/g;s/å/%E5/g'`
log=sms-log.txt
cookie=sms-cookie.txt
page1=sms-login.html
page2=sms-mypage.html
page3=sms-receipt.html
wget --cookies=on --keep-session-cookies --save-cookies=$cookie -o $log -O $page1 https://www.gulesider.no/mypage/loginForm.c
wget --cookies=on --keep-session-cookies --save-cookies=$cookie -a $log -O $page2 --load-cookies=$cookie --referer=https://www.gulesider.no/mypage/loginForm.c https://www.gulesider.no/mypage/login.c --post-data="username=$username&password=$password&x=30&y=10"
wget --cookies=on --keep-session-cookies --save-cookies=$cookie -a $log -O $page3 --load-cookies=$cookie https://www.gulesider.no/mypage/sendSms.c --post-data="submit=Send&sender=$sender&recipients=$to&text=$msg"
if egrep -q 'Din melding er sendt' $page3
then
 echo OK!
 rm $log $page1 $page2 $page3 $cookie
else
 echo "Oops, something may have gone wrong. See files: $log, $page1, $page2, $page3, $cookie" >&2
 exit 1
fi

