#!/usr/local/bin/perl5 -w
#	Add latest Parameter Information to file
#
require "cgi-lib.pl";
$mailprog = '/usr/lib/sendmail';
#
$filetologto = '';
$statusofread =  &ReadParse(*formdata);
$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';
}
#
#	Base URL
$baseforparmstore = "/usr/local/archives/public/html/users/gcf/nobody/webwisdom/";
#
$today =`date`;
chomp($today);
#
$baseforparmstore .= $userdir .'/';
#
$filetologto = $baseforparmstore . 'hostdefaultlog';
$parmstoreerrorflag=0;
if(-e $filetologto )	{
	open(FILETOLOGTO,'>>'.$filetologto) || ($parmstoreerrorflag=1);
}
else	{
	open(FILETOLOGTO,'>'.$filetologto) || ($parmstoreerrorflag=1);
	print FILETOLOGTO "Log of Parameter Save Actions\n";
}
if( $parmstoreerrorflag == 1 )	{
	print "Location: http://www.npac.syr.edu/users/gcf/webwisdom/SavedLogError.html\n\n";
	exit 1;
}
#
#
if( $statusofread )	{
	if( (exists($formdata{'hostfilename'})) && (defined($formdata{'hostfilename'})) )	{
		$filetosaveto = $formdata{'hostfilename'};
	}
	else	{
		$filetosaveto = 'hostdefault';
	}
	$filetosaveto = $baseforparmstore . 'parmsets/' .  $filetosaveto;
#
	$count = 0;
	while (!&LockDatabase($filetosaveto)) { # Sleep for a second
	        sleep(1);
	        ++$count;
	        &therewaserror("Server out to lunch -- please email -- lock stuck") if($count > 20);
	}
#
	open(FILETOSAVETO,'>'.$filetosaveto) || ($parmstoreerrorflag=1);
	if( $parmstoreerrorflag == 1 )       {
		&logerror();
		print "Location: http://www.npac.syr.edu/users/gcf/webwisdom/SavedError.html\n\n";
		&UnlockDatabase($filetosaveto);
		exit 1;
	}
	print FILETOSAVETO "Title:List of Parameters \n";
	print FILETOSAVETO 'Date:',$today,"\n";
	foreach $name (sort keys(%formdata))	{
		next if( $name eq 'SaveOnHost' );
		print FILETOSAVETO $name,':',$formdata{$name},"\n";
	}
	print FILETOSAVETO "Status:OK\n";
	print FILETOSAVETO "Remoteaddr:",$ENV{'REMOTE_ADDR'},"\n";
	print FILETOSAVETO "Remotehost:",$ENV{'REMOTE_HOST'},"\n";
	close(FILETOSAVETO);
	&UnlockDatabase($filetosaveto);
	print FILETOLOGTO 'OK ',$today,' ',$filetosaveto,' ',$ENV{'REMOTE_ADDR'},' ',$ENV{'REMOTE_HOST'},"\n";
}
else	{
	$parmstoreerrorflag=1;
	&logerror();
}
close(FILETOLOGTO);
if( $parmstoreerrorflag == 1 )	{
	print "Location: http://www.npac.syr.edu/users/gcf/webwisdom/SavedError.html\n\n";
}
else	{
	print "Location: http://www.npac.syr.edu/users/gcf/webwisdom/SavedOK.html\n\n";
}
#
sub	logerror	{
#
	return unless $filetologto;
	print FILETOLOGTO 'Failed ',$today,' ',$ENV{'REMOTE_ADDR'},' ',$ENV{'REMOTE_HOST'},"\n";
#
}
#
sub therewaserror       {

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

<html>
<head>
<title>Error in saveparms.pl Processing!</title>
</head>
<h2>Error in Processing Parameter Set Save: $mess</H2>
Please correct or if it's our fault
<A HREF="mailto:gcf\@npac.syr.edu?subject=saveparms.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 saveparms.pl
EOF
                close(MAIL);
        }
}
#
1;

