#!/usr/local/bin/perl

# sms-itineris: send a Short Message to a GSM cell phone through Itineris.
# Written by Ch. Tronche (http://tronche.lri.fr:8000/)
# Copyright by the author. This is unmaintained, no-warranty free software. 
# Please use freely. It is appreciated (but by no means mandatory) to
# acknowledge the author's contribution. Thank you.
# Started on Mon Mar 17 16:03:24 1997
#
# V1.01 28/01/1999
# Now take gateway quota exceeded into account.
#

use FileHandle;
use Socket;

use strict 'refs';
use strict 'subs';
use integer;

$IPPROTO_TCP = 6;
$sockaddr = 'S n a4 x8';

$calepin = $ENV{HOME}.'/.pager-calepin';

if ($ARGV[1] eq '-notify') {
    $_ = $notify = $ARGV[2];
    splice @ARGV, 1, 2;
    if (!/\@.+\./o || /\@.*\@/o) {
	warn "Invalid email address $_, no notification will occur\n";
	undef $notify;
    }
}

if (!@ARGV || $#ARGV > 1 || $ARGV[0] eq '-help') {
    die "Usage: sms-itineris dest [-notify me\@address] [ message ]\n";
}

$abonne = shift;
if (@ARGV) {
    $message = shift;
} else {
    $message .= $_ while(<>);
}

if ($abonne !~ /^\d+$/o) {
    open(CALEPIN, "<$calepin") || die "I can't open your directory file '$calepin'";
    while(<CALEPIN>) {
	chop;
	($name, $number) = split /\t+/o;
	if ($name eq $abonne) {
	    $abonne = $number;
	    last;
	}
    }
    die "I haven't found $name in your directory file '$calepin'" unless $abonne =~ /^\d+$/o;
}

$message =~ s/([^a-zA-Z0-9])/sprintf "%%%02X", ord($1)/geo;
$message =~ s/%20/+/go;
$message = substr($message, 0, 160);
$left = 160 - length $message;
$message = "number=$abonne&message=$message&left=$left&email=$notify&x=0&y=0";
$length = length $message;
($name, $aliases, $type, $len, $addr) = gethostbyname('sms.itineris.tm.fr');
$addr || die("unknown host sms.itineris.tm.fr ?");

for(;;) {
    socket(COMMAND, AF_INET, SOCK_STREAM, $IPPROTO_TCP) || die "socket ($!)";
    $sock = pack($sockaddr, AF_INET, 80, $addr);

    connect(COMMAND, $sock) || die "I can't contact the Itineris SMS gateway ($!)";
    autoflush COMMAND 1;

    print COMMAND <<END;
POST /cgi-bin/post-sms HTTP/1.0
User-Agent: tronche's itineris SMS sender (http://www-ihm.lri.fr/~tronche/misc/pager/SMS-itineris/)
Content-type: application/x-www-form-urlencoded
Content-length: $length

$message
END
    $wait = 0;
    while(<COMMAND>) {
        $wait = $1 if /Vous pourrez.*essayer dans (\d+) seconde/o;
        $wait = $1 * 60 if /Vous pourrez.*essayer dans (\d+) minute/o;
    }
    if (!$wait) {
       exit(0);
    }
    print STDERR "Gateway quota exhausted, waiting for $wait seconds\n";
    sleep($wait);
}
