#!/usr/bin/perl -w

use strict;
use Getopt::Long;
use vars qw($opt_n $opt_h $opt_m $opt_c $opt_H $opt_S $opt_C $PROGNAME);

my $tmp="/tmp/";
my $prefix="";
my $filename="$$";
my $asterisk_sounds=$prefix."/var/lib/asterisk/sounds/voicealerts/";
my $asterisk_spool=$prefix."/var/spool/asterisk/outgoing/";
my $txt2pho=$prefix."/usr/local/mbrola/txt2pho/txt2pho -f -p ".$prefix."/usr/local/mbrola/txt2pho/data/ ";
my $voice="de3/de3";
my $mbrola=$prefix."/usr/local/mbrola/mbrola ".$prefix."/usr/local/mbrola/voices/".$voice." - ".$tmp.$filename.".wav";
my $sox="/usr/bin/sox ".$tmp.$filename.".wav -t wav -r 8000 - > ".$asterisk_sounds.$filename.".wav";
my $unlink="/usr/bin/unlink ".$tmp.$filename.".wav";

$PROGNAME = "call.pl";

sub print_help($);

Getopt::Long::Configure('bundling');
GetOptions 
  ("n:s" => \$opt_n, "number"     => \$opt_n,
   "c:s" => \$opt_c, "callerid"   => \$opt_c,
   "C:s" => \$opt_C, "channel"    => \$opt_C,
   "H:s" => \$opt_H, "host"       => \$opt_H,
   "S:s" => \$opt_S, "service"    => \$opt_S,
   "h"   => \$opt_h, "help"       => \$opt_h);

while(<STDIN>) {
 $opt_m.=lc $_;
}

print_help ("") if($opt_h);
($opt_n) || print_help("Number not specified\n");
($opt_m) || print_help("No message specified\n");
($opt_C) || print_help("No channel specified\n");
($opt_c) || print_help("No Callerid specified\n");
($opt_c) || print_help("No Host specified\n");

my $syntax='echo "'.$opt_m.'"|'.$txt2pho.'|'.$mbrola;
system($syntax);
system("$sox");
system("$unlink"); 

my $output="";
$output.="Channel: $opt_C\n";
$output.="MaxRetries: 2\n";
$output.="RetryTime: 60\n";
$output.="WaitTime: 30\n";
$output.="Context: Voicealerts\n";
$output.="Extension: s\n";
$output.="Priority: 1\n";
$output.="Callerid: $opt_c\n";
$output.="Set: MSG=voicealerts/".$filename."\n";
$output.="Set: CONTACT=$opt_n\n";
$output.="Set: HOST=".$opt_H."\n";
$output.="Set: SERVICE=$opt_S\n";
open(OUT,"> ".$asterisk_spool.$filename.".call");
print OUT $output;
close(OUT);

exit 0;

sub print_help ($) {
   my ($message) =@_;
   print "Usage: $PROGNAME -n <number/name> -c <callerid> -C <channel> -H <host> -S <service>\n";
   print $message."\n";
   exit 0;
}
