#!/usr/bin/perl -Tw 

use strict;
use CGI;

my $cgi = new CGI;

#my $supportAddress = $cgi->param('emailAddress');
my $supportAddress = "anxvpnlogs\@opentext.com";
my $userName = $cgi->param('userName');
my $commentsName = $cgi->param('commentsName');
my $commentsCompany = $cgi->param('commentsCompany');
my $commentsBody = $cgi->param('commentsBody');

#$supportAddress = "anxvpnlogs\@opentext.com" unless ( length( $supportAddress ) > 0 );

my $boundary = "SUPPORT-ATTACHMENT-BOUNDARY";

my $from = "\"Support tool\" <$supportAddress>";
my $subjectString = "Log files for user $userName";
my @bodyString = qq(Attached are log files generated from the support tool and any support questions the user has.\n\nUser Email: $commentsName\nCompany: $commentsCompany\n$commentsBody);

my $i = 1;

my @attachments = ();

while(1)
{
	my $buf;
	my $uf;

	my $file = $cgi->upload('file' . $i);

	$file eq '' and last;

	while (sysread($file,$buf,512))
	{
		$uf .= $buf;
	}

	my $attachments = "--$boundary\nContent-Type: application/octet-stream\nContent-Description: " . $cgi->param('file'.$i) . "\nContent-transfer-encoding: base64\nContent-Disposition: attachment; filename=\"" . $cgi->param('file' . $i) . "\"\n\n$uf\n";

	push(@attachments,$attachments);

	$i++;
}

$ENV{'PATH'} = "/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin";
email( to=> $supportAddress, from=> $from, subject=> $subjectString, body=> @bodyString, attachments=> \@attachments, boundary=> $boundary );

print "Content-type: text/html\n\n
			SupportTool";


sub email
{
	my ($subject,$from,$body,$to,$attachments,$boundary) = @{{@_}}{qw/subject from body to attachments boundary/};

	my $bto;
	my $cto;

	if ( ref($to) eq "ARRAY" )
	{
		$bto = join(', ',@{ $to });

		my @goodCtos = ();

		foreach my $badCto ( @{ $to } )
		{
			$badCto =~ s/(\W)/\\$1/g;
			push @goodCtos, $badCto;
		}

		$cto = join(' ',@goodCtos);
		$cto =~ /^(.*)$/;
		$cto = $1;
	}
	else
	{
		$bto = $to;
		$cto = $to;

		$cto =~ s/(\W)/\\$1/g;
		$cto =~ /^(.*)$/;
		$cto = $1;
	}

	$ENV{'PATH'} = "/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin";
	open(MAILPIPE,"| sendmail $cto");
	print MAILPIPE "MIME-Version: 1.0\n";
	print MAILPIPE "From: $from\n";
	print MAILPIPE "To: $bto\n";
	print MAILPIPE "Subject: $subject\n";
	print MAILPIPE "Content-Type: multipart/mixed; boundary=\"$boundary\"\n\n";
	print MAILPIPE "--$boundary\n";
	print MAILPIPE "Content-Type: text/plain; charset=\"iso-8859-1\"\n\n";
	print MAILPIPE "$body\n";
	
	foreach my $attach (@{ $attachments })
	{
		print MAILPIPE "$attach";
	}
	print MAILPIPE "--$boundary--";
	close(MAILPIPE);
}

