#!/usr/bin/perl

%filename =
  (
   "about.html", 1,
   "list.html", 1,
   "skeptic_faq.html", 1,
   "admin/addresses", 1,
  );


unshift(@INC, "lib");

require 'config.pl';
require 'web.pl';
require 'cgi-lib.pl';

$temp = "$db::dir/temp$$";

&ReadParse; # Read the script input
print "Content-type: text/html\n";

# Determine if we are running as an administrator
&error("Cannot run this CGI except from the admin subdir!")
  unless $ENV{SCRIPT_NAME} =~ m!/admin/!;

if ($in{filename})
{
    &error("Not a valid filename: $in{filename}")
      unless $filename{ $in{filename} };

    $filename = "$bib::base_dir/$in{filename}";
}

# If they selected a filename, display it for editing
if ($filename)
{
    # If they're submitting this form, write and exit
    &write_file_and_exit() if $in{data};

    open(FILE, $filename)
      || &error("Cannot read file $filename: $!");

    undef $/; # read whole file at once

    $file_data = <FILE>;

    close(FILE);
    $data = &bib::template("edit-info2.html",
                           "FILENAME", $in{filename},
                           "DATA", &untaint($file_data));
}
else
{
    # If they haven't selected anything, display the initial form
    foreach (sort keys %filename)
    {
        $filenames .= "<OPTION>$_";
    }

    $data = &bib::template("edit-info.html",
                           "FILENAMES", $filenames);
}

print "\n", &bib::template("basic.html",
                           "TITLE", "Edit Info File",
                           "DATA", $data);

exit 0;


sub write_file_and_exit
{
    open(TMP, ">$temp") || &error("Cannot write temp file $temp: $!");
    print TMP $in{data};
    close TMP;

    unless (rename($temp, $filename))
    {
        unlink $temp;
        &error("Cannot rename temp file '$temp' to '$filename': $!");
    }

    chmod 0664, $filename;

    &success("Successfully updated file " .
             "<A HREF=\"$bib::base/$in{filename}\">$in{filename}</A><P>\n" .
             "<A HREF=$bib::admin_cgi/edit-info.cgi>Edit other files</A>");
}
