#!/usr/bin/perl -w

# This CGI script gives a friendly user interface
# to the directory where ATT dumps the call detail
# reports. It allows you to view the files as text, download
# the files, download them as CSV files, or clean up
# old files.

use CGI qw/:standard/;
use strict;

# testing on bitsy.sub-atomic.com
(-d "/home/liveops/ssh") && chdir("/home/liveops/ssh");
# live config
(-d "/home/adl/users/liveops/cdr") && chdir("/home/adl/users/liveops/cdr");

my $i = 0;
my $dmax = param('dmax');
if (defined $dmax) {
	foreach $i (0 .. $dmax) {
		my $f;
		if ($f = param("d$i")) {
			unlink($f);
			Delete("d$i");
		}
	}
	Delete('dmax');
}

# show the file they are asking for, if and only if they ask
# for a simple filename
my $f = param('file');
if (defined $f && $f =~/^[a-z0-9_.]*$/i) {
	if (open(O, "<$f")) {
		if (param('dl')) {
			if (param('cs')) {
				printCSV();
				exit;
			}
			print header(-type => "application/binary",
				'-Content-Disposition' => "attachment; filename=\"$f\"");
		} else {
			print header("text/plain");
		}
		print <O>;
		close(O);
	} else {
		print header(-type=> "text/plain", -status=>404);
		print "File $f not found.";
	}
	exit;
}

print header("text/html");
print "<script type=\"text/javascript\" src=\"checkAllIpb.js\"></script>";

my @files = <*.rpt>;

$i = 0;
print start_form(-name => 'listform');

print "<table>\n";
print "<tr><th>", checkbox(-name => 'allbox', -label=>'', onclick => "CheckAll(document.listform);");
print "<th>Filename<th>Summary\n";

foreach my $file (@files) {
	my $summary = getSummary($file);

	param('file', $file);
	my $furl = self_url();
	param('dl', 1);
	my $dlurl = self_url();
	Delete('dl');

	my $csurl = '';
	if ($summary ne 'Bulk Data Download') {
		param('dl', 1);
		param('cs', 1);
		$csurl = self_url();
		Delete('cs');
		Delete('dl');
	}

	print "<tr>";
	print "<td>", checkbox(-name=>"d$i", -value=> $file, -label=>'', onclick => "CheckCheckAll(document.listform);");
	print "<td><a href=\"$furl\">$file</a>";
	print " <a href=\"$dlurl\"><img border=0 src=\"document-save.png\"></a>";
	print " <a href=\"$csurl\"><img border=0 src=\"csv.gif\"></a>"
		unless $csurl eq '';
	print "<td>$summary";
	print "\n";

	$i++;
}
print "</table>\n";

$i--;
print "<input type=hidden value=\"$i\" name=dmax>";

print "<input type=button value=\"  Remove selected...  \"
	onclick=\"confirm('Are you sure you want to remove the files?')?document.listform.submit():false\">";
print end_form();

# try to make a one-line description of the file
sub getSummary {
	my ($file) = @_;
	if (! open(F, "<$file")) {
		return '(not found)';
	}

	my $name = 'unknown name';
	my $date = 'unknown date';
	my $debug = '';
	my $end;

	while (<F>) {
		chomp;
		s/^\s*//;		# clean off front
		s/SCD: /SCD\t/;	# make it properly tab delimited
		s/: \t?/\t/;

		if (/Bulk Data Download/) {
			close F;
			return "Bulk Data Download";
		}

		my($k, $v) = split(/\t/);
		$debug .= "$k, ";

		if (defined $k && $k eq 'SCD') {
			$name = $v;
			$name =~ s/^Standard Call Detail //;
		}

		if (defined $k && $k eq 'Requested Date(s)') {
			$date = $v;
			last;
		}
	}
	close F;
	return "$name, $date"; #$debug";
}

sub printCSV {
	my($file) = param('file');

	if (! open(F, "<$file")) {
		print header(-type=> "text/plain", -status=>404);
		print "File $f not found.";
		exit;
	}

	$file =~ s/.rpt$/.csv/;
	print header(-type => "text/csv",
		'-Content-Disposition' => "attachment; filename=\"$file\"");

	my $mode;
	$_ = <F>;
	if (/^SCD/) {
		$mode = 1;
		$_ = <F>;
		$_ = <F>;
	} else {
		$mode = 2;
		while (<F>) {
			last if (/^----/);
		}
		$_ = <F>;
		$_ = <F>;
		$_ = <F>;
		$_ = <F>;
	}

	my @line;
	while (<F>) {
		if ($mode == 1) {
			@line = split(/\t/);
			shift @line;
			shift @line;
			$line[3] =~ s/^\s*//;
		} elsif ($mode == 2) {
			s/ +/\t/g;
			@line = split(/\t/);
			shift @line;
		}

		print $line[3], ",", $line[4], "\n"
			if (defined $line[3] && $line[3] ne '');
	}
	close F;
}