#!/usr/bin/perl -w
use strict;
# Simple sms sending.
# Uses the clickatell API 
# http://www.clickatell.com/downloads/Clickatell_http_2.2.2.pdf
# huw@munted.org
# TODO improve error checking/handling

# Takes the reipient list as args. Expects msg on STDIN
# e.g echo "some text" |./clickatell_alert.pl 447789232836
# Dont bother with a leading '+' or '0' on the tel num

use LWP;

# Clickatell config
my $user = 'your_username';
my $pass = 'the_password';
my $url_base = 'http://api.clickatell.com/http';
my $api_id = 'your_api_id';
# end config
my $debug = 0; # Mmmmmmmmm cheese

my $msg;
while (<STDIN>) {
	$msg .= $_;
}
$msg = substr($msg,0,156); # max sms length

my $ua = new LWP::UserAgent;
$ua->agent("Mozilla/4.0");
my $sid = &get_sessid();
my @failures;

foreach my $number (@ARGV) {
	$number =~ s/\+//;
	&send_sms($number,$msg);
}

exit 0 if !@failures;

if (defined $debug) {
	my $err = join('\n', @failures);
	print $err;
}

print "Error\n" if !defined $debug;
exit 1;

# Subs
sub send_sms {
	my $to = $_[0];
	my $message = $_[1];
	my $url = $url_base."/sendmsg?session_id=$sid&to=$to&text=$message";
	my $req = HTTP::Request->new(POST => $url);
	$req->content_type('application/x-www-form-urlencoded');
	my $res = $ua->request($req);
	if ($res->is_success) {
		print $res->content if defined $debug;
		my ($status,$id) = split /:/,$res->content;
		push @failures, "Error sending message with id :- $id\n" if ($status =~ /ERR/);
		print "\nMessage send was succesfull\n" if (defined $debug && $status =~ /ID/);
	}
	else {
		push @failures, "Clickatell returned an error.";
	}
}

sub get_sessid {
	my $url = $url_base."/auth?api_id=$api_id&user=$user&password=$pass";
	my $req = HTTP::Request->new(GET => $url);
	$req->header('Accept' => 'text/html');
	my $res = $ua->request($req);
	if ($res->is_success) {
		my ($result,$id) = split /:/,$res->content;
		die "Cant get a sessid :- $id\n" if ($result =~ /ERR/);
		$id =~ s/\s//;
		return $id;
	}
	else {
		die "Unable to authenticate to the clickatell gateway\n";
	}
}
