#!/usr/bin/perl

use File::Temp qw(tempfile);
use File::Copy;


my $from;
my $channel = "CAPI/1234:b0193010";
my $context = "smsdial";
my $extension = $ARGV[0];
my $maxlen = 160;
my $spooldir = "/var/spool/asterisk/outgoing";
my $msg;

my $inbody = 0;
while (<STDIN>)
{
  chop;
  if (/^$/ and $inbody == 0)
  {
    $inbody = 1;
    next;
  }

  if ($inbody == 0)
  {
    if (/^From: (.*)$/)
    {
      $from = $1;
    }
  }
  else
  {
    $msg .= $_ . " ";
  }
}

if ($from =~ /<(.*@.*)>$/)
{
  $from = $1;
}

$msg = substr($msg,0,$maxlen);

my($fh, $filename) = tempfile();

print $fh <<EOD;
Channel: $channel
MaxRetries: 2
RetryTime: 60
WaitTime: 30
Context: $context
Extension: $extension
Priority: 1
SetVar: MSG=$msg
EOD

close($fh);

move $filename, $spooldir;
