#!/usr/bin/perl

# Mail to SMS gateway script, version 1.0
# By Andy Hawkins (andy@gently.demon.co.uk)

# Set this to be the path to your mail program

$MAILER="/usr/lib/sendmail -t";

# Set this to the maximum number of tries for a message

$retries=5;

$foundblank=0;
$number="";

headerloop: while(<>)
{
	chomp;
	if (/^From:\s(\S+)/)
	{
		$fromaddr=$1;
	}

	if (/^Subject:\s(\S+)/)
	{
		$number=$1;
	}

	if (/^$/)
	{
		$foundblank=1;
		last headerloop;
	}
}

$msg="";

messageloop: while (<>)
{
	chomp;
	last messageloop if /^quit$/ or /^end$/;

	if ($msg)
	{
		$msg=$msg." ".$_;
	}
	else
	{
		$msg=$_;
	}
}

print "Message is to $number\n";

print "Message is ($msg)\n";

$success=0;
$longmsg=0;
$badservice=0;
$badnumber=0;

if ($number)
{
	sendloop: while ($retries)
	{
		$retcode=system ("/usr/bin/sms_client $number \"$msg\"")/256;
#		$retcode=system ("exitstat.pl $number \"$msg\"")/256;
		if ($retcode==0)
		{
			$success=1;
			last sendloop;
		}
		else
		{
			print "Failed with retcode $retcode\n";
			if ($retcode==1)
			{
				$longmsg=1;
				last sendloop;
			}
	
			if ($retcode==3)
			{
				$badservice=1;
				last sendloop;
			}
	
			if ($retcode==4)
			{
				$badnumber=1;
				last sendloop;
			}
		
			sleep 5;
			$retries--;
		}
	}
}
	
open MAIL,"|$MAILER";

#print MAIL "From: $MAIL_FROM\n";
print MAIL "To: $fromaddr\n";

if ($success)
{
	print MAIL "Subject: SMS to $number sent successfully\n";
	print MAIL "\n";

	print MAIL "Your SMS to $number was sent successfully\n";
}
else
{
	print MAIL "Subject: SMS to $number failed\n";
	print MAIL "\n";

	print MAIL "Your SMS to $number failed\n";

	unless ($number)
	{
		print MAIL "No number found in subject header\n";
	}

	if ($longmsg)
	{
		print MAIL "Your message was too long\n";
	}

	if ($badservice)
	{
		print MAIL "An invalid service was specified\n";
	}

	if ($badnumber)
	{
		print MAIL "The number $number could not be expanded\n";
	}
}

close MAIL;
