#!/usr/local/bin/perl5 -w
#	SEt up Advanced Dump Option
#
require "cgi-lib.pl";
$mailprog = '/usr/lib/sendmail';
#
$statusofread =  &ReadParse(*formdata);
#
$advanceddumperrorflag =0;
#
$userdir = 'defaultuser';
if( $statusofread && exists($formdata{"username"}) ) {
        $userdir = $formdata{"username"} if( defined($formdata{"username"}) );
}
$testuserdir = $userdir;
$testuserdir =~ tr/A-Z/a-z/;
if( ($testuserdir eq 'guest') || ($testuserdir =~ m%^anon%) )   {
        $userdir = 'defaultuser';
}
#
$countoffiles = 0;
$audiodir = '';
$audiofiletype = '.aifc';
$audiomonitortime = 0;
$advanceddumperrorflag = 1 unless( $userdir eq 'gcf' );
#
unless($advanceddumperrorflag)	{
	if( $statusofread )	{
		$advanceddumperrorflag = 2 unless(exists($formdata{"audiodir"}));
		$advanceddumperrorflag = 2 unless(exists($formdata{"audiofiletype"}));
		$advanceddumperrorflag = 2 unless(exists($formdata{"audiomonitortime"}));
		unless($advanceddumperrorflag)	{
			$audiodir = $formdata{"audiodir"};
			$audiofiletype = $formdata{"audiofiletype"};
			$audiomonitortime = $formdata{"audiomonitortime"};
			$advanceddumperrorflag = 2 unless( (defined($formdata{"audiodir"})) && $audiodir ne '');
			$advanceddumperrorflag = 3 unless( (defined($formdata{"audiofiletype"})) && $audiofiletype ne '' );
			$advanceddumperrorflag = 3 unless(defined($formdata{"audiomonitortime"}));
		}
		unless($advanceddumperrorflag)  {
			$advanceddumperrorflag = 4 unless( -r $audiodir);
		}
	}
}
#
unless($advanceddumperrorflag)  {
	getlist();
}
#
$today =`date`;
chomp($today);
#
$filetologto = "/usr/local/archives/public/users/gcf/nobody/webwisdom/" .$userdir .'/hostdefaultlog';
#
$count = 0;
while (!&LockDatabase($filetologto)) { # Sleep for a second
        sleep(1);
        ++$count;
        &therewaserror("Server out to lunch -- please email -- lock stuck") if($count > 20);
}
#
$filelogerror =0;
if(-e $filetologto )    {
	open(FILETOLOGTO,'>>'.$filetologto) || ($filelogerror=1);
}
else    {
	open(FILETOLOGTO,'>'.$filetologto) || ($filelogerror=1);
	print FILETOLOGTO "Log of Parameter Save Actions\n";
}
unless($filelogerror)	{
	print FILETOLOGTO 'Advanced Dump On ',$audiodir,' Type ',$audiofiletype,' ',$today,' ',$userdir,' ',$advanceddumperrorflag,' ',$ENV{'REMOTE_ADDR'},' ',$ENV{'REMOTE_HOST'},"\n";
	close(FILETOLOGTO);
}
else	{
	$advanceddumperrorflag =8;
}
#
&UnlockDatabase($filetologto);
#
if( $advanceddumperrorflag <= 2 )	{
	$advanceddumperrorflag = 0;
}
#
if( $advanceddumperrorflag )	{ # Error of Some Sort
	print <<EOF;
Content-Type: text/html

<html>
<head>
<title>Error in Set of Advanced Dump Options</title>
<script language="JavaScript">
</script>
</head>
<script language="JavaScript">
<!--scriptbegin
document.writeln('<body background="' + top.bigboss.wisdomhomeurl + '../background/' + top.bigboss.currentparameters.bgfile + '"  >');
document.writeln('<font size=3 color="' + top.bigboss.currentparameters.imgfgcolor + '" >');
//scriptend-->
</script>
<h2>Error in Set of Advanced Dump Options</h2>
Note this is currently only set up for local NPAC Experiments and will
<UL>
<li>Allow User Specification of URL Recording
<li>Will Monitor Audio Recording
</ul>
<hr>
</form>
<form name="formtodump" ACTION="http://boss.npac.syr.edu:8080/cgi-bin/webwisdom/advanceddump.pl" METHOD="post"
ENCTYPE="application/x-www-form-urlencoded"  >
<input type="submit" name="List" value="Set Options" ><br>
<script language="JavaScript">
<!--scriptbegin
document.writeln('Audio Monitor Directory<input name="audiodir" type="text" value="' + top.bigboss.audiodir + '" ><br>');
document.writeln('Audio FileType<input name="audiofiletype" type="text" value="' + top.bigboss.audiofiletype + '" ><br>');
document.writeln('Audio Monitoring Update Interval in Seconds<input name="audiomonitortime" type="text" value="' + top.bigboss.audiomonitortime + '" ><br>');
document.writeln('<input name="username" type="hidden" value ="' + top.bigboss.username + '" ><br>');
//scriptend-->
</script>
<br>
</form>
</body>
</html>
EOF
	exit;
}	# End Error Processing
#
#	Succesful Setup of Advanced Dump Options
        print <<EOF;
Content-Type: text/html

<html>
<head>
<title>Succesful Setup of Advanced Dump Options</title>
<script language="JavaScript">
<!--scriptbegin
function setformvalues()     {
	top.bigboss.audiodir = document.forms[0].elements[0].value;
	top.bigboss.audiofiletype = document.forms[0].elements[1].value;
	top.bigboss.audiomonitortime = document.forms[0].elements[2].value;
	top.bigboss.setupadvanceddump();
}
//scriptend-->
</script>
</head>
<script language="JavaScript">
<!--scriptbegin
document.writeln('<body onload="setformvalues();" background="' + top.bigboss.wisdomhomeurl + '../background/' + top.bigboss.currentparameters.bgfile + '"  >');
document.writeln('<font size=3 color="' + top.bigboss.currentparameters.imgfgcolor + '" >');
//scriptend-->
</script>
<H2>Advanced Dump Options Succesfully Set Up</H2>
Please Rejoice and Continue with WebWisdom<br>
<form name="goodoptions" >
Audio Monitor Directory<input name="audiodir" type="text" value ="$audiodir" ><br>
Audio FileType<input name="audiofiletype" type="text" value ="$audiofiletype" ><br>
Audio Monitoring Update Interval in Seconds<input name="audiomonitortime" type="text" value ="$audiomonitortime" ><br>
</form>
EOF
	if($countoffiles)	{
	print "<h3>Current Files of Specified Type</h3>\n<form>\n";
	print 'Number of Files<input name="numfiles" type="text" size="40" value="' . $countoffiles . '" ><br>' ."\n";
	for($i=0;$i<$countoffiles;$i++)	{
		$file = $chompedfiles[$i];
		print 'File '.$i. '<input name="file' .$i. '" type="text" size="40" value="' . $file . '" ><br>' ."\n";
	}
	print "</form>\n";
	}
        print <<EOF;
</body>
</html>
EOF
	exit;
#
sub getlist     {
#
	$com = 'ls -t ' . $audiodir . '/*' . $audiofiletype;
        @listoffiles = `$com`;
        $countoffiles=0;
        foreach $file (@listoffiles)    {
                chomp($file);
                next unless $file;
                $chompedfiles[$countoffiles] = $file;
                $countoffiles++;
        }
}
sub therewaserror       {

        my($mess) = @_;
#
        print <<EOF;
Content-Type: text/html

<html>
<head>
<title>Error in advanceddump.pl Processing!</title>
</head>
<h2>Error in Processing URL Advanced Logging: $mess</H2>
Please correct or if it's our fault
<A HREF="mailto:gcf\@npac.syr.edu?subject=advanceddump.pl Lock Error $mess" onMouseOver="window.status=' Sadness!.';return true">Mail Complaint</A>
<hr>
EOF
        exit;
}
sub LockDatabase {
# PURPOSE: Attempt to "lock" the database by creating a lock file.
# INPUTS:  Database file name
# OUTPUTS: A boolean telling if the lock was successful

        my ($dbfile) = @_;

        if (-e "$dbfile.lock") {  # DB is already locked
                return 0;
        }
        else {
                system("touch $dbfile.lock");  # Create the lock file
                return 1;
        }
}

sub UnlockDatabase {
# PURPOSE: Attempt to "unlock" the database by deleting the lock file.
# INPUTS:  Database file name
# OUTPUTS: None (but should probably check that the unlock was successful)

        my ($dbfile) = @_;
        unless( (unlink("$dbfile.lock")) )      {
                open (MAIL, "|$mailprog gcf") || (&therewaserror("Server Error Can't Mail -- Please email us")) ;
                print MAIL <<EOF;
From:gcf
To:gcf
Subject:Error in unlink
------------------------------------------------------

Please check advanceddump.pl
EOF
                close(MAIL);
        }
}
#
sub cgidebug    {

open(DEBUGFILE,'>>/usr/local/archives/public/users/gcf/nobody/webwisdom/debug') || return;
foreach $val (@_)       {
        if(defined($val) )      {
                print DEBUGFILE $val,' ';
        }
        else    {
                print DEBUGFILE 'Undefined ';
        }
}
print DEBUGFILE "\n";
close(DEBUGFILE);
return;
}
#
1;

