#!/usr/bin/perl

use Asterisk::AGI;
use File::Basename;
use Digest::MD5 qw(md5_hex);
  
# Edit these to match your system.
my $dir = "/var/lib/asterisk/sounds/festival/"; 
my $app = '/usr/bin/text2wave';
my $scale = 4;
 
 # Create the AGI interface.
$AGI = new Asterisk::AGI;
my %input = $AGI->ReadParse();

# Setup the necessary variables.
my ($text) = join (' ', @ARGV);
my $hash = md5_hex($text);
my $cache = ($0 =~ /cache-festival\.pl$/ ? 1 : 0);
my $textfile = $dir . ($cache ? 'cache' : 'temp') .  "_" . $hash . ".txt";
my $wavefile = $dir . ($cache ? 'cache' : 'temp') .  "_" . $hash . ".wav";
  
# Create the wave file if it does not already exist.
unless (-f $wavefile) {
    open (TEXT, ">$textfile") or die "Could not write text file: $!";
    print TEXT "$text";
    close (TEXT);
    my $execf = "$app -F 8000 -scale $scale -o $wavefile $textfile";
    system ($execf);
}

# Play the wave file
$dir =~ s/.*\/([^\/]+\/)$/$1/;
$AGI->stream_file($dir . basename ($wavefile, ".wav")); 

# Delete the temp files if we are not to cache them.
unlink ($textfile, $wavefile) unless $cache;
