#!/usr/bin/perl -w
#
# Typical script for submitting an SMS message to a WWW gateway
#
# This script requires POST from the Perl LWP package.

my $url = 'http://put.your.web.2.sms.gateway.here/foo/bar.cgi';
my $email = 'your@email.here';
my $password = 'your_password';
my $mobile = '0123456789';
my $CGI_params = 'email=$email&password=$password&mobile=$mobile&network=1&text=$message&Submit=Submit';

##############################################################################

use strict;
use Getopt::Std;

my %opts = ();
getopts('dho', \%opts);

my $prog = $0;
$prog =~ s!.*/!!;

die <<USAGE if @ARGV or $opts{h};
Usage: $prog [ -d ] [ -o ] < message_file
   -d  Dummy run - send to STDOUT instead of phone
   -o  Show output
USAGE

my $message = join '', <STDIN>;

chomp $message;

# Quote characters which won't get through the gateway otherwise
my $pre_length = length $message;
$message =~ s!([^\w/])!sprintf "%%%02x", ord($1)!eg;
$message =~ s/\s*\n+\s*/ /g;

$CGI_params =~ s/(\$\w+)/$1/eeg;  # Need an EEG after understanding this
my $length = length $CGI_params;

my $content_type = 'application/x-www-form-urlencoded';

if ($opts{d}) {
  print "Length: $pre_length\n$CGI_params\n";
}
else {
  my $command = "POST -e -c $content_type $url";
  $command .= " >&/dev/null" unless $opts{o};
  open(POST, "|$command")
    or die "Couldn't pipe to POST: $!\n";
  print POST $CGI_params;
  close(POST);
}
