#!/usr/local/bin/perl5 -w
#	Add Session Information to file
#
require "cgi-lib.pl";
$mailprog = '/usr/lib/sendmail';
#
$statusofread =  &ReadParse(*formdata);
$userdir = 'defaultuser';
if( $statusofread && exists($formdata{"user"}) ) {
        $userdir = $formdata{"user"} if( defined($formdata{"user"}) );
	$userdir =~ s%^([^\@]*)\@(.*)$%$1%;
}
$userdir =~ s%\s+%_%g;
$userdir =~ s%\W+%X%g;
$testuserdir = $userdir;
$testuserdir =~ tr/A-Z/a-z/;
if( ($testuserdir eq 'guest') || ($testuserdir =~ m%^anon%) )   {
        $userdir = 'defaultuser';
}
$userdir = 'defaultuser' if( $userdir ne 'gcf' );
#
#	Base URL
$basefordumping = "/usr/local/archives/public/users/gcf/nobody/webwisdom/";
#
$today =`date`;
chomp($today);
#
$basefordumping .= $userdir .'/edit/';
#
$foilset = 'UNKNOWN';
if(exists($formdata{'foilset'}))	{
	$foilset = $formdata{'foilset'} if(defined($formdata{'foilset'}));
}
$foilsetdir =$foilset;
$foilsetdir =~ s/\W/_/g;
#
$sessionfile='errorlog';
if( $statusofread )     {
	$sessionfile = $formdata{'session'};
	$sessionfile =~ s%\s+%_%g;
	$sessionfile =~ s%\W+%X%g;
}
#
$filetodumpto = $basefordumping . $foilsetdir;
unless(-e $filetodumpto)	{
	mkdir $filetodumpto,0777;
}
else	{
	unless(-d $filetodumpto)	{
		&gcferror("$filetodumpto is not a directory");
		print "Location: http://boss.npac.syr.edu:8080/webwisdom/editutilities/SessionDumpError.html\n\n";
		exit 1;
	}
}
#
$filetodumpto = $filetodumpto .'/'. $sessionfile;
#
$count = 0;
while (!&LockDatabase($filetodumpto)) { # Sleep for a second
        sleep(1);
        ++$count;
        &therewaserror("Server out to lunch -- please email -- lock stuck") if($count > 20);
}
#
#
$dumperrorflag=0;
if(-e $filetodumpto )	{
	open(FILETODUMPTO,'>>'.$filetodumpto) || ($dumperrorflag=1);
}
else	{
	open(FILETODUMPTO,'>'.$filetodumpto) || ($dumperrorflag=2);
}
if( $dumperrorflag > 0 )	{
	print "Location: http://boss.npac.syr.edu:8080/webwisdom/editutilities/SessionDumpError.html\n\n";
	&UnlockDatabase($filetodumpto);
	exit 1;
}
#
print FILETODUMPTO "sessionstart:$foilset\n";
$typeofform = 'UNKNOWN';
if(exists($formdata{'typeofform'}))	{
	$typeofform = $formdata{'typeofform'} if(defined($formdata{'typeofform'}));
}
print FILETODUMPTO "sessiontype:$typeofform\n";
unless( $typeofform =~ /set/ )	{
	$foilnumber = 'UNKNOWN';
	if(exists($formdata{'foilnumber'}))	{
		$foilnumber = $formdata{'foilnumber'} if(defined($formdata{'foilnumber'}));
	}
	print FILETODUMPTO "sessionfoilnumber:$foilnumber\n";
}
$sessionname = 'UNKNOWN';
if(exists($formdata{'session'}))      {
	$sessionname = $formdata{'session'} if(defined($formdata{'session'}));
}
print FILETODUMPTO "sessionname:$sessionname\n";
$sessionuser= 'UNKNOWN';
if(exists($formdata{'user'}))	{
	$sessionuser= $formdata{'user'} if(defined($formdata{'user'}));
}
print FILETODUMPTO "sessionuser:$sessionuser\n";
$sessionpassword= 'UNKNOWN';
if(exists($formdata{'password'}))	{
	$sessionpassword= $formdata{'password'} if(defined($formdata{'password'}));
}
print FILETODUMPTO "sessionpassword:$sessionpassword\n";
$easytoday = `date '+%Y/%m/%d/%H/%M/%S'`;
chomp($easytoday);
$epochtime = time;
print FILETODUMPTO "sessiontime:$epochtime : $easytoday : $today\n";
print FILETODUMPTO "sessionaddress:$ENV{'REMOTE_ADDR'}\nsessionhost:$ENV{'REMOTE_HOST'}\n";
#
if( $statusofread )	{
	foreach $mem (sort keys %formdata)	{
		next	if( $mem =~ m%^CHG% );
		next if( $mem =~ m%^browse% );
		next if( $mem eq 'maxfoilnumber' );
		next if( $mem eq 'typeofform' );
		next if( $mem eq 'password' );
		next if( $mem eq 'user' );
		next if( $mem eq 'foilset' );
		next if( $mem eq 'foilnumber' );
		next if( $mem eq 'session' );
		if(exists($formdata{'CHG'.$mem}))	{
			my($testval) = $formdata{'CHG'.$mem};
			next if($testval =~ m%^n%i );
		}
		$val = $formdata{$mem};
		next if( $val eq 'UNSET' );
		next if( $val eq 'UNIMPLEMENTED' );
		next if( $val eq 'Replace with Text' );
		$val =~ s%[\n\r\f]+%\nCONTD:%gs;
		$val =~ s%\nCONTD:$%%s;
		print FILETODUMPTO "$mem:$val\n";
	}
}
else	{
	$dumperrorflag=3;
	print FILETODUMPTO "Error:3\n";
}
print FILETODUMPTO "sessionend:$foilset\n";
close(FILETODUMPTO);
#
&UnlockDatabase($filetodumpto);
#
if( $dumperrorflag > 0 )	{
	print "Location: http://boss.npac.syr.edu:8080/webwisdom/editutilities/SessionDumpError.html\n\n";
}
else	{
	print "Location: http://boss.npac.syr.edu:8080/webwisdom/editutilities/SessionDumpOK.html\n\n";
}
sub therewaserror       {

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

<html>
<head>
<title>Error in savesession.pl Processing!</title>
</head>
<h2>Error in Processing URL Logging: $mess</H2>
Please correct or if it's our fault
<A HREF="mailto:gcf\@npac.syr.edu?subject=savesession.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")) )      {
		&gcferror('unlink');
	}
	return;
#
}	# End UnlockDatabase
#
sub	gcferror	{
#
	open (MAIL, "|$mailprog gcf") || (&therewaserror("Server Error Can't Mail -- Please email us")) ;
        print MAIL <<EOF;
From:gcf
To:gcf
Subject:Error in $_[0]
------------------------------------------------------

Please check savesession.pl
$ENV{'REMOTE_ADDR'} $ENV{'REMOTE_HOST'},
$formdata{"user"}
$formdata{"session"}
$sessionfile
$userdir
DUMP Error Indicator $dumperrorflag
$today
EOF
        close(MAIL);
	return;
#
}	#	End gcferror
#
#
1;

