#! /usr/bin/perl -w 
#
# This script is intended to be used together with procmail.
# If will send a sms with the subject as the text. The 
# receiver is either specified as an command line argument
# or extracted from the To: header field from the mail.
#
# If an command line argument is specified the it is used
# as the receiver, if not then what comes before the @ in 
# the to field is used. In both cases the receiver can be
# specified with a name from the addressbook, or with a 
# number (like 079xxxxxxx), a country code prepended with 
# a - (like 41-79xxxxxxx).
#
# In all cases the subject will be the text of the sms.
#
# Possible use:
#
# You can send an sms by sending an email to a (sub)domain.
# E.g. you can use the subdomain sms.yourdoain.com, so an
# email to jan@sms.yourdomain.tld will send an sms to the 
# entry 'jan' from the addressbook. 
# Add something like the following three lines to 
# procmailrc to make this work.
#
# :0:
# * TO.*@sms.yourdomain.tld
# | mail2sms   
# 
# Another possible use it you can send an sms to yourself 
# whenever you get an email from a specific person. E.g.
# if you want to be notified with an sms whenever you get
# an email from George Bush put the following in your 
# .procmailrc
#
# :0c:
# * From: president@whitehouse.gov
# | mail2sms <your number>
#
# Check man pages for procmail, procmailrc, and procmailex
# for explanation of the above procmail code.
#
# author: jan.sorensen@aragost.com
#

use strict;

my $to = shift;
my $subject = "ERRRO IN $0: NO SUBJECT FOUND";
my $test = 0;

while(<>) {
    if (m/^To: *(.*)@.*/) { $to = $1 unless $to; };
    if (m/^Subject: *(.*)/) { $subject = $1; }
    if (m/^Testing/) { $test = 1; } # useful when testing with stdin on command line
}

$to || die "$0: Receiver for sms could not be extracted" ;

my $cmd = "echo $subject | linuxsms";

# Check if we have a number or a name from the address book
if ($to =~ m/^((\d*)\-)?(\d*)$/) {
    # There can be an optional country code before a - (e.g. 41-79xxxxxxxx)
    $cmd .= " -number:$3";
    $cmd .= " -prefix:$2" if $2;
} else {
    $cmd .= " -name:$to";
}

if ($test) {
    print "cmd: $cmd";
} else {
    system $cmd;
}