#!/usr/bin/perl
# (c) 2009, Christopher Jansen
#
# Distributed under the same terms as Perl itself.
#
# Simple AGI to use Festival to say something, because I couldn't get app_festival to work.
# If you're using Ubuntu 8.10, just 'aptitude install festival libasterisk-agi-perl' 
# and this'll work fine.
use strict;
use Asterisk::AGI;
use FileHandle;

$|=1;

my $output_path = "/tmp";

my $AGI = new Asterisk::AGI;
my %in = $AGI->ReadParse();
my $text = $ARGV[0];
my $donotspeak = $ARGV[1];
my $filename = $ARGV[2];
print STDERR "Using filename $output_path/$filename\n";
createfile($text,\$filename);
saytext($filename) unless($donotspeak);
exit(0);

sub getfnbase($)
{
  my $text = shift;
  my $fn   = $text;
  $fn =~ s/[^A-Za-z0-9]+/-/g;
  return $fn;
}

sub saytext($)
{
  my $fn   = shift;
  die("No file to stream") unless($fn);
  print STDERR "Preparing to stream file: $output_path/$fn\n";
  die("Cannot stream text") if($AGI->stream_file("$output_path/$fn") == -1);
  print STDERR "Done streaing file: $output_path/$fn\n";
}

sub createfile($$)
{
  my $text = shift;
  my $fn   = shift;
  $$fn ||= getfnbase($text);

  if(!-e "$output_path/$$fn.wav")
  {
    my $tf = new FileHandle("> $output_path/$$fn.txt");
    $tf->print($text);
    $tf->close();
  }
  `text2wave $output_path/$$fn.txt -f 8000 -o $output_path/$$fn.wav`;
}

