#!/usr/bin/perl

$logfile="logfile";
$width=80;
$tmpdir="tmp";
$finaldir="entries";
$urlbase="http://www.demo.cs.brandeis.edu/Private/info";
$thisform="infoform.cgi";
$masterpasswd="33665";
$runindexgen="/usr/bin/perl ./indexgen";
$nopassword=1;

use CGI;
$query = new CGI;

print $query->header;
print "<head><title>DEMO information post form</title></head>
    <body >\n";

if ($query->param('entry')) {
   print "<p><h2 align=center>MODIFICATION FORM</h2><p>\n";
   $continue=undef;
   $delete=undef;
   $entry=$query->param('entry');
   if ( -f "$finaldir/$entry.post") {
       if ($query->param('pass')) {
	   open IN,"<$finaldir/$entry.post";
	   $oldquery = new CGI(IN);
	   close IN;
	   print "olquery loaded title=",$oldquery->param('title'),
		 "<br>\n";

	   if ($query->param('delete')) {
	       $delete=1;
	       }
	   if ($nopassword || $masterpasswd eq $query->param('pass')) {
	       $continue=1;
	       }
	   elsif  ($oldquery->param('pass') && 
	       ("" ne trim($oldquery->param('pass')))) {
	       if ($oldquery->param('pass') eq $query->param('pass')) {
		   #passwd ok!
		   print "<p>password ok.<p>";
		   $continue=1;
		   }
		else {
		   print "<p>wrong password<p>";
		   }
		}
	    else {
		print "<p>Entry can't be modified.<p>";
		}
	    }
	else {
	  # create a little form for password input
	  print "<form action=$thisform method=post>\n";
	  if (!($nopassword)) {
	    print 	      "Enter password: ",
	    $query->password_field(-name=>'pass');
	  }
	  else {
	    print $query->hidden(-name=>'pass', -value=>$masterpasswd);
	  }
	  print $query->hidden(-name=>'entry'),
	  "<br>",
	  "<p>Click here to modify this entry: ",
	  $query->submit(-name=>"modify"),
	  "<P>Click here to delete it : ",
	  $query->submit(-name=>"delete"),
	  $query->endform;
       }
   }
   else {
       print ("<p>Error: Can't find entry\n<p>");
   }
    if ($continue) {
	$query=$oldquery;
	if ($delete) {
	    print "<p> deleting ",$query->param('title'),"<p>";
	    $id=$query->param('id');
	    foreach $ext (qw(post idx html 0.html)) {
		$file="$finaldir/$id.$ext";
	        # print ("$tmpfile -> $file <br>\n");
	        if (-f "$file.old") {
		    unlink ("$file.old");
	        }
	        if (-f $file) {
		    link($file,"$file.old");
		    unlink($file);
	        }
	    }
	    spawn_reindex();
	    print "<p> Deleted. <p>",
	    "<a href=$urlbase>Click here to go back to the ",
	    "DEMO Private Parts</a> <p>\n",
	    "Remember to reload the page to see your changes.<P>\n";
	   $|=1;
	   exit(0);
	

	}
	# print "<p> modify ",$oldquery->param('title'),"<p>";
	print "<p> modify ",$query->param('title'),"<p>";
	}
    else {
	$|=1;
	# print "<P>EXIT 0<P>";
	exit (0);
    }
}

if ($query->param('finish')) {
  $id=$query->param('id');
  foreach $ext (qw(post idx html 0.html)) {
    $file="$finaldir/$id.$ext";
    $tmpfile="$tmpdir/$id.$ext";
    if (-f $tmpfile) {
      # print ("$tmpfile -> $file <br>\n");
      if (-f "$file.old") {
	unlink ("$file.old");
      }
      if (-f $file) {
	link($file,"$file.old");
	unlink($file);
      }
      link($tmpfile,$file);
      unlink($tmpfile);
    }
    else {
      print "<b>Error: $tmpfile does not exist. Double submission?</b><br>\n";
    }
  }
  spawn_reindex();

  print "<b>Done.<br> 
  <a href=$urlbase>Click here to go back to the 
DEMO Private Parts</a></b>\n",
    "Remember to reload the pages to see your changes<p>\n";
   exit(0);
  }

elsif ($query->param('submit')) {
  print "<h1>FORM RECEIVED</h1>";
    $errors=undef;
    # check for errors
    # 1. check that a title is present
    if (trim($query->param('title')) eq '') {
      $errors=1;
      print ("<p><b>Error: No title.</b><p>");
    }
    @curtime=localtime(time);
    $day=$curtime[3];
    $month=$curtime[4]+1;
    $year=$curtime[5]+1900;
     
    #datestring="".(($year+2)*10000+$month*100+$day);
    $datestring="29990101"; # default expiration date
    $todaystring="".($year*10000+$month*100 + $day);
    #2. check for correct expiration date
     if ("" ne trim($query->param('expdate'))) {
       if ($query->param('expdate') < $todaystring) {
 	print ("<p><b>Warning: Expiration date past already</b></p>");
       }
       #lsif (($query->param('pass') ne $masterpasswd) && 
	#     ($query->param('expdate') > $datestring)) {
	# print("<p><b>Error: Expiration date after two years</b></p>");
	#$errors=1   ;
       #
     }
     else {
       #print "<p><b>Expiration date set by default to $datestring</b><p>\n";
       $query->param('expdate', $datestring);
       }
    $_ = $query->param('section');
    s/ .*$//;
    if ($_ eq "00") {
	print("<b><p>Error: Please select a section</p></b>");
	$errors=1 ;
	}
    if ($errors) {
      print  "<p><b>YOUR FORM CONTAINS ERRORS. \n",
	     "PLEASE CORRECT THE INFORMATION BELOW AND RESUBMIT</p></b>\n";
    }
    else {
      # no errors, go ahead
      # do we have an id yet?
      if (! $query->param('id')) {
	# no, create new one
	$query->param('id',time);
      }
      $id=$query->param('id');
      # ok, now we have an id
      # generate random password if one not present
      if (! $query->param('pass')) {
	$query->param('pass',randstring(5));
      }
	
      print  "<p><b>No errors, processing entry $id...</b></p>\n";

      
      #create files
      # 1. full post file
      open(OUT,">$tmpdir/$id.post") or die "Can't open $id.post";
      $query->save(OUT);
      close OUT;
      # 2. index entry
      open(OUT,">$tmpdir/$id.idx") or die "Can't open $id.idx";
      print OUT $query->param('expdate')," ",
      $query->param('id')," ",
      $todaystring," ",
      $query->param('section'),
      "\n";
      close OUT;
      # 3. formatted entry
      open OUT,">$tmpdir/$id.html" or die "Can't open $id.html";
      print OUT formatentry("$finaldir/");
      close OUT;
      #4. optional page
      open OUT, ">$tmpdir/$id.0.html" or die "Can't open $id.0.html";
      print OUT 
	"<html><head><title>",$query->param('title')," ",
	$query->param('detttitle'),"</title></head>
<body bgcolor=white>
<a href=\"$baseurl\">Back to the DEMO Lab Private Parts</a>
<h1 align=center>",$query->param('title'),"</h1>
<h3 align=center>",$query->param('dettitle'),"</h3><p><hr><p>";
      print OUT $query->param('detail');
      close OUT;
      #now display the formated entry...
      print  "<hr>",
      "<h3>",$query->param('section'),"</h3>\n",
      "<blockquote><p>\n",
      formatentry("$tmpdir/"),
      "<p></blockquote><p>\n";
    }
    print "<hr>\n";
    #print "<p>Expiration date: ",$query->param('expdate'),"<br>\n",
    #"Password: ",$query->param('pass'),"<br>\n",
    #"Email: ",$query->param('email'),"<br>\n",
    #"<hr>\n";
  if (!$errors) {
  print "<p>",$query->startform,
      $query->hidden(-name=>'id',-value=>$id),
      $query->submit(-name=>'finish',
	  -value=>'Click here to finish your submission'),
      $query->endform,
      "<br>Or<br>\n";
    }
   print "<a href=/>Click here to cancel and go back to the DEMO info page</a><br>
Or correct the information below and submit again.
<p><hr>";
  display_form();
}

else {
  #if ($query->param('password') eq $masterpasswd) {
    display_form();
  #}
  # else  {
  #   print "Please go to the <a href=limbo>DEMO Limbo</a> 
  #to make postings\n";
  #   exit(0);
  # }
  #display_form();
}

sub display_form {
    print "<h1 align=center>DEMO Info post form</h1
    Use this page to post information for the Lab's Page
    <p>

    ";
    print $query->startform;
    print "
    Section:<br>
    ";
    @sections=("00 ** Choose a section ** ");
    open IN,"<sections";
    while (<IN>) {
      push(@sections,$_);
    }
    print $query->popup_menu('section',\@sections);
    print "<p>Title: (required) <br>\n",
	$query->textfield(-name=>'title',
			  -size=>$width),
	"<p>Description: (html) <br>\n",
	$query->textarea(-name=>'descr',
			 -cols=>$width,
			 -rows=>5),

#	"<p>Expiration date: (optional, enter yyyymmdd or leave blank for no ex)<br>\n",
#	$query->textfield(-name=>'expdate',-size=>8,-maxsize=>8),
	"<p>Web address: (optional)<br>\n",
	$query->textfield(-name=>'http',
			  -default=>'http://',-size=>$width),
	"<p><blockquote>Detailed information (optional)<br>",
	"<i>You can include a long html text, a 
	 full description, a report or essay, etc. </i><br>\n",
	"<p>Title (i.e. \"abstract\",\"report\", etc.)<br>\n",
	$query->textfield(-name=>'dettitle',-size=>30),
	"<br>Full Text: Use html or, if text preferred, enter &lt;PRE&gt; in the first line<br>\n",
	
	$query->textarea(-rows=>30, -cols=>$width, -name=>'detail'),
	"</blockquote><br>\n";
#	"<p>A password... (optional, you'll need it only if you wish to modify/delete this entry<br>\n",
#        $query->textfield(-name=>'pass',-size=>10),
#        "<p>An email address... (if you want the system to notify you when ",
#        "this entry is about to expire)<br>\n",
#	$query->textfield(-name=>'email',-size=>25);
    if ($query->param('id')) {
      print $query->hidden('id');
    }
    print 	"<p>",
                        "<ul><li>",
	$query->submit(-name=>'submit',
	    -value=>"Click here to submit"),
	"(you'll still have another chance of reviewing)",
	"<li>",
	'<a href=".">Or click here to cancel and go back 
	to the DEMO Lab Info Page</a>',
	$query->endform;
    }

sub trim {
    # remove leading & trailing spaces from a string
    # and chomp it.
    $_ = $_[0];
    chomp;
    s/^ *//;
    s/ *$//;
    return $_;
   }

sub formatentry {
  local($prefix)=$_[0];
  local($t)="";   
  local ($h)=$query->param('http');
  if ($h) {
    $h=trim($h);
    if ($h eq "http://" || $h eq "") {
      $h=undef;
    }
  }
  $h =~ s/http:\/\/http:\/\//http:\/\//;
  if ($h) {
    $t=$t."<a href=\"$h\"><b>".$query->param('title')."</b></a>\n";
  }
  else {
    $t=$t."<b>".$query->param('title')."</b>\n";
  }
  $t=$t."<br>\n".$query->param('descr')."\n";
  if ($query->param('detail') && "" ne trim($query->param('detail'))) {
    if ("" eq trim($query->param('dettitle'))) {
      $query->param('dettitle','In more Detail...');
    }
    $t=$t."<br>&nbsp;&nbsp;&nbsp;".
      "<a href=\"".$prefix.$query->param('id').".0.html\"><i>".
      $query->param('dettitle')."</i></a>";
  }
  $t=$t."<p>\n";
  return $t;
}

sub randstring {
  local($t)="";
  for ($i=0;$i< $_[0]; $i++) {
    $t=$t.chr(65 + int rand(26));
  }
  return $t;
}

sub spawn_reindex {
    # return ;
    # flush stdout
    select(STDERR); $| = 1;
    select(STDOUT); $| = 1;
    local($pid)=fork();
    if ($pid == 0) {
	# i'm the child process
	# 1. close stdout&stderr (to free the httpd pipe)
	# 1a. first dup stdout/err
	open OLDOUT,">&STDOUT" or print "error 1<br>";
	open OLDERR,">&STDERR" or print "error 2<br>";
	# 1b. now create new ones pointing to logfile
	open STDOUT, ">$logfile" or print "error 3<br>";
	open STDERR, ">&STDOUT" or print "error 4<br>";
	# 1c. make them unbuffered
	select(STDERR); $| = 1;
	select(STDOUT); $| = 1;
	# 1d. release inherited out/err
	close OLDOUT or print "error 5<br>";
	close OLDERR or print "error 6<br>";
	# process entry
	system($runindexgen);
	# 3. child exits
	exit(0);
    } 
}
