#!/usr/bin/perl

use lib $ENV{'SERVER_LIBEXEC'};

use TGI;
use Sys::Syslog;

openlog('TGI', 'nowait', 'daemon');

$ani = "unknown";
$name = "unknown caller";
$subject = undef;
$from = undef;
$sender = undef;
$to = undef;
$cc = undef;
$bc = undef;
$deliver = undef;
$msgfile = undef;
$filename = undef;
$msgid = undef;

@header = undef;
@footer = undef;

$hostname = `hostname`
$filename = $TGI::QUERY{filename} if $TGI::QUERY{filename};
$header = $TGI::QUERY{header} if $TGI::QUERY{header};
$footer = $TGI::QUERY{footer} if $TGI::QUERY{footer};
$msgfile = $TGI::QUERY{msgfile} if $TGI::QUERY{msgfile};
$msgid = $TGI::QUERY{msgid} if $TGI::QUERY{msgid};
$subject = $TGI::QUERY{subject} if $TGI::QUERY{subject};
$from = $TGI::QUERY{from} if $TGI::QUERY{from};
$sender = $TGI::QUERY{sender} if $TGI::QUERY{sender};
$deliver = $TGI::QUERY{deliver} if $TGI::QUERY{deliver};
$to = $TGI::QUERY{to} if $TGI::QUERY{to};
$cc = $TGI::QUERY{cc} if $TGI::QUERY{cc};
$bc = $TGI::QUERY{bc} if $TGI::QUERY{bc};
$ani = $TGI::ANI if $TGI::ANI;

$name = $TGI::ANI if $TGI::ANI;
$name = $TGI::CID{name} if $TGI::CID{name};

if($TGI::QUERY{header})
{
	open(HEADER, $TGI::QUERY{header});
	@header = <HEADER>;
	close(HEADER);
}

if($TGI::QUERY{footer})
{
	open(FOOTER, $TGI::QUERY{footer});
	@footer = <FOOTER>;
	close(FOOTER);
}

if(!$msgfile)
{
	syslog('crit', 'no file to deliver');
	closelog();
	die;
}

if(! -f $msgfile)
{
	syslog('crit', 'message file %s missing', $msgfile);
	closelog();
	die;
}

if(!$deliver)
	{$deliver = $to;};

if(!$to)
	{$to = $deliver;};

if(!$deliver)
{
	syslog('crit', 'no user to deliver to');
	closelog();
	die;
}

if(!$subject)
	{$subject = "VPIM Message";}

if(!$sender)
	{$sender = "non-mail-user@$hostname";}

if(!$msgid)
	{$msgid = time(); $msgid = "$msgid$port@$hostname";}

if(!$from)
	{$from = "$name";}

if(!$filename)
	{$filename = $msgfile};

open(OUTPUT, "|/usr/sbin/sendmail -f$sender $to");
open(AUDIO, "mmencode -b <$msgfile|");

print OUTPUT "From: $from <$sender>\n";
print OUTPUT "To: $to\n";
if($cc)
	print OUTPUT "CC: $cc\n";

if($bc)
	print OUTPUT "BC: $bc\n";

if($subject)
	print OUTPUT "Subject: $subject\n";

print OUTPUT "Message-id: <$msgid>\n";
print OUTPUT "MIME-Version: 1.0 (Voice 2.0)\n";
print OUTPUT "Content-Type: multipart/voice-message;\n";
print OUTPUT "  boundry=\"attachment\"\n\n";

if(@HEADER)
{
	print OUTPUT "--attachment\n";
	print OUTPUT "Content-Type: text/html;\n";
	print OUTPUT "Content-Transfer-Encoding: ascii\n\n";
	print OUTPUT "@HEADER\n";
}

print OUTPUT "--attachment\n";
print OUTPUT "Content-Type: audio/x-wav;\n";
print OUTPUT "  name=\"`basename $filename`.wav\"\n";
print OUTPUT "ContentTransfer-Encoding: base64\n\n";

print OUTPUT <AUDIO>;

close(AUDIO);

if(@FOOTER)
{
	print OUTPUT "--attachment\n";
	print OUTPUT "Content-Type: text/html;\n";
	print OUTPUT "Content-Transfer-Encoding: ascii\n\n";
	print OUTPUT "@FOOTER\n";
}

print OUTPUT "--attachment--\n";

close(OUTPUT);


