#!/usr/bin/perl

# Change openimpetus invocation of perl
# chmod -R a+w .../openimpetus

my ($mydir, $i, @oi, $orig, @hints, $keeplooping, $constants_backup_open,
    $crap);
my $perl=0;
my $dir="";
my $constants="";
my @constants_hints;

$|=1;

print "This is the configuration script for openimpetus.\n";
print "\n";

$mydir=$0;
$mydir=~s/Configure.pl$//;
chdir($mydir) || die "Can't chdir to where Configure.pl resides ($mydir)!\n";

&say("I'm going to look around and figure what's up; if I can't figure
it out, I'll ask you and maybe provide a default answer.  If you don't
know the correct answer, just use the default (by hitting RETURN).");

if (-r "$ENV{HOME}/.openimpetus_configuration_hints") {
  open(HINTS, "$ENV{HOME}/.openimpetus_configuration_hints");
  print "Reading hints file...\n";
  $perl=<HINTS>;  chop($perl);
  $dir=<HINTS>;  chop($dir);
  $constants=<HINTS>;  chop($constants);
  if ($constants ne "") {
    if (open(CONSTANTS_HINTS, $constants)) {
      while(<CONSTANTS_HINTS>) {
	chop;
	push(@constants_hints, $_);
      }
      close(CONSTANTS_HINTS);
    }
  }
  print "done";
}

if ($perl!=0) {
  if (!(-x $perl)) {
    print "Can't execute '$perl'!\n";
    $perl=0;
  }
}
if ($perl==0) {
  print "Let's see where perl might reside...\n";
  if (-x "/usr/bin/perl") {
    $perl=1;
  } elsif (-x "/bin/perl") {
    $perl=2;
  } elsif (-x "/usr/local/bin/perl") {
    $perl=3;
  }
}
while ($perl==0) {
  &say("Can't find where perl lives; please enter the absolute
pathname to the perl executable: ");
  $_=<>;
  chop;
  if (-x $_) {
    $perl=$_;
  } else {
    print "'$perl' is not executable.\n";
  }
}

push(@hints, $perl);

$perl="#!".$perl;
open(OI, "openimpetus.pl") || die "Can't open openimpetus.pl for reading!\n";
$_=<OI>;
if ($_ eq $perl) {
  close(OI);
} else {
  push(@oi, $perl);
  while(<OI>) {
    push(@oi, $_);
  }
  close(OI);
  open(OI, ">openimpetus.pl") ||
    die "Can't open openimpetus.pl for writing!\n";
  for ($i=0;$i<=$#oi;$i++) {
    print OI $oi[$i];
  }
}

################

chdir("Comps") || die "Can't chdir to Comps !\n";

if ($dir eq "") {

  &say("OpenImpetus is capable of keeping track of separate
competitions' information in parallel; this is done by keeping each
comp's info in a separate directory structure.  What directory name
should I use for your comp?  A short name with no spaces would be
good; for instance: 'MIT', 'HarvardBeginner', 'BU_Beginner'");
  print "Comp directory name: ";
  
  $_=<>;
  chop;
  $orig=$_;
  s/\s/_/g;
  $dir=$_;
  if ($orig ne $dir) {
    print "I'm going to use '$dir' for the directory name.\n";
  }
}

push(@hints, $dir);

@dirs=($dir, "$dir/Catl", "$dir/Cats", "$dir/Name", "$dir/School",
       "$dir/Templates", "$dir/Mail", "$dir/PS", "$dir/Images");

print "Creating/updating the directory structure...";

while(shift(@dirs)) {
  if (-d $_) {
    if (chmod(0777, $_)==0) {
      die "Can't chmod 777 $_ !\n";
    }
  } else {
    if (mkdir($_, 0777)) {
      die "Can't mkdir($_)!\n";
    }
  }
}
print "  done.\n";

chdir($dir);

################

$constants_backup_open=0;
if ($constants ne "") {
  if (open(CONSTANTS_BACKUP, ">$constants")) {
    $constants_backup_open=1;
  }
}

if ($#constants_hints==-1) {
  $constants="$ENV{HOME}/.openimpetus_constants" if ($constants eq "");

  &say("OK, you need a Constants file to configure your site.  I'll walk
you through this process.");
  &say("First off: where should we save this when
we're all done?  There's a canonical location that I'll save a copy,
but it's nice to have a backup, so we only have to do this once.");
  print "Backup file: [$constants] ";

  $keeplooping=1;
  while($keeplooping) {
    $_=<>;
    chop;
    if (//) {
      $target=$constants;
    } else {
      $target=$_;
    }
    if (open(CONSTANTS_BACKUP, ">$target")) {
      $keeplooping=0;
    } else {
      print "Couldn't open '$target'; please re-specify:\n[$constants] ";
    }
  }  
  &build_constants_file(\*CONSTANTS_BACKUP) if ($#constants_hints==-1);
}
&modify_constants_file(\@constants_hints);

################

&say("Should I initialize the database?  This will erase everthing in
it.  You will want to do this if this is the first time you are
configuring OpenImpetus.  Initializing the db will entail removing it,
touching the file, and then setting write permissions on it.");

$db="$mydir/Comps/$dir/database";
print "Initialize db ('$db')? [n] ";
$_=<>;
if (/y/i) {
  unlink("$db");
  system("touch $db");
}
chmod(0666, "$db");

exit(0);

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

sub build_constants_file {
  my $OUT=@_[0];
  my ($starting_number, $last_number, $server, $stats_dir_href, $form_url,
      $compname, $registrar_realname, $registrar_title, $registrar_email,
      $sig, $sig_href, $sig_value, $text, $bgcolor, $link, $vlink,
      $background);

  &say("OK, I'm going to ask you some questions about your comp.
Let's start off with some easy stuff.  Every leader gets a number --
what should be the lowest number?");

  $starting_number=100;
  &prompt(\$starting_number);
  print "And the last number?\n";
  $last_number=399;
  &prompt(\$last_number);
  print "\n";

  &say("OK, now the server is going to have to write to files; what is
the path to the OpenImpetus directory?");

  &prompt(\$dir);
  print "And what is the full name of the web server?\n";
  print "(E.g., 'wombat.mit.edu'): ";
  &get_data(\$server);

  &say("Alright; you'll probably need to set up an Alias that redirects
HTTP requests correctly into your filesystem (see the README file for
more information).  What is the Alias that points into
'$mydir/Comps/$dir/'?");

  &get_data(\$stats_dir_href);
  print "Right.  What is the URL for openimpetus.pl ?\n";
  $form_url="/openimpetus/openimpetus.pl";
  &prompt(\$form_url);
  print "And just for the openimpetus directory?\n";
  $stats_url="/openimpetus/";
  &prompt(\$form_url);

  print "\n";

  print "OK, less gory stuff.\n";
  print "Like...  what is the name of your Comp?\n";
  &get_data(\$compname);
  print "Full name of the Registrar?\n";
  &get_data(\$registrar_realname);
  print "Registrar's full title?  (E.g., 'MIT Competition Registrar')\n";
  &get_data(\$registrar_title);
  print "Registrar's email address?\n";
  &get_data(\$registrar_email);

  &say("OK, each OpenImpetus page will have a little section at the end of
each page; if you understand HTML code, it'll be");
  print "\t<hr>\n";
  print "\t<i>SIG (<a href=SIG_HREF>SIG_VALUE</a>)</i>\n";
  print "What should SIG be?  (E.g., 'The MIT Ballroom Dance Team')\n";

  &get_data(\$sig);
  print "What should SIG_HREF be?  (E.g., 'mailto:mitbdt-captain\@mit.edu')\n";
  &get_data(\$sig_href);
  print "And SIG_VALUE?  (E.g., 'mitbdt-captain\@mit.edu')\n";
  &get_data(\$sig_value);

  print "\n";

  &say("Fun stuff: what should the color text be?  Specify either a
color that HTML will like ('white', 'black', 'yellow', etc) or a hex
code ('#ddeeff'): ");

  $text="white";
  &prompt(\$text);
  print "And the background color?\n";
  $bgcolor="white";
  &prompt(\$bgcolor);
  print "Unfollowed links should be what color?\n";
  $link="yellow";
  &prompt(\$link);
  print "And followed links?\n";
  $vlink="orange";
  &prompt(\$vlink);
  print "Lastly, what URL should be used for the background image?\n";
  $background="/openimpetus/Images/background.gif";
  &prompt(\$background);

  print "\n";

  print "Whew.\n\n";

  &say("OK, I'm going to create a bunch of files for you.  It won't
look exactly the way you want it to, of course, but at least the files
will be out there, and then you can look at the Aesthetics Tweaking
chapter of the Site Configuration manual to make it look perfect.");

  push(@out, "starting_number=$starting_number");
  push(@out, "last_number=$last_number");
  push(@out, "server=$server");
  push(@out, "stats_dir_href=$stats_dir_href");
  push(@out, "form_url=$form_url");
  push(@out, "compname=$compname");
  push(@out, "registrar_realname=$registrar_realname");
  push(@out, "registrar_title=$registrar_title");
  push(@out, "registrar_email=$registrar_email");
  push(@out, "sig=$sig");
  push(@out, "sig_href=$sig_href");
  push(@out, "sig_value=$sig_value");
  push(@out, "text=$text");
  push(@out, "bgcolor=$bgcolor");
  push(@out, "link=$link");
  push(@out, "vlink=$vlink");
  push(@out, "background=$background");

  for ($i=0;$i<=$#out;$i++) {
    print $OUT $out[$i]."\n";
  }
  close($OUT);

  &modify_constants_file(\@out);
}

sub modify_constants_file {
  my $constants_hints_ref=@_[0];
  my ($i, @constants_hints);
  my ($starting_number, $last_number, $server, $stats_dir_href, $form_url,
      $compname, $registrar_realname, $registrar_title, $registrar_email,
      $sig, $sig_href, $sig_value, $text, $bgcolor, $link, $vlink);

  @constants_hints=@$constants_hints_ref;

  $i=0;
  ($crap, $starting_number)=split('=', $constants_hints[$i++]);
  ($crap, $last_number)=split('=', $constants_hints[$i++]);
  ($crap, $server)=split('=', $constants_hints[$i++]);
  ($crap, $stats_dir_href)=split('=', $constants_hints[$i++]);
  ($crap, $form_url)=split('=', $constants_hints[$i++]);
  ($crap, $compname)=split('=', $constants_hints[$i++]);
  ($crap, $registrar_realname)=split('=', $constants_hints[$i++]);
  ($crap, $registrar_title)=split('=', $constants_hints[$i++]);
  ($crap, $registrar_email)=split('=', $constants_hints[$i++]);
  ($crap, $sig)=split('=', $constants_hints[$i++]);
  ($crap, $sig_href)=split('=', $constants_hints[$i++]);
  ($crap, $sig_value)=split('=', $constants_hints[$i++]);
  ($crap, $text)=split('=', $constants_hints[$i++]);
  ($crap, $bgcolor)=split('=', $constants_hints[$i++]);
  ($crap, $link)=split('=', $constants_hints[$i++]);
  ($crap, $vlink)=split('=', $constants_hints[$i++]);
  ($crap, $background)=split('=', $constants_hints[$i++]);

  open(CON, "Constants") || die "Can't open Constants for reading!\n";
  while(<CON>) {
    push(@con, $_);
  }
  close(CON);

  open(CON, ">Constants") || die "Can't open Constants for writing!\n";
  while(<CON>) {
    if (/^STARTING_NUMBER/) {  s/=(.*)$/=$starting_number/;  }
    if (/^LAST_NUMBER/) {  s/=(.*)$/=$last_number/;  }
    if (/^SERVER/) {  s/=(.*)$/=$server/;  }
    if (/^STATS_DIR_HREF/) {  s/=(.*)$/=$stats_dir_href/;  }
    if (/^FORM_URL/) {  s/=(.*)$/=$form_url/;  }
    if (/^COMPNAME/) {  s/=(.*)$/=$compname/;  }
    if (/^REGISTRAR_REALNAME/) {  s/=(.*)$/=$registrar_realname/;  }
    if (/^REGISTRAR_TITLE/) {  s/=(.*)$/=$registrar_title/;  }
    if (/^REGISTRAR_EMAIL/) {  s/=(.*)$/=$registrar_email/;  }
    if (/^SIG/) {  s/=(.*)$/=$sig/;  }
    if (/^SIG_HREF/) {  s/=(.*)$/=$sig_href/;  }
    if (/^SIG_VALUE/) {  s/=(.*)$/=$sig_value/;  }
    if (/^BODY_TAG/) {
      $_="BODY_TAG=\"<BODY bgcolor=\\\"$bgcolor\\\" text=\\\"$text\\\" link=\\\"$link\\\" vlink=\\\"$vlink\\\" background=\\\"$background\\\">\"\n";
    }

    print CON $_;
  }  
  close(CON);
}

sub prompt {
  my $default_ref=@_[0];
  my $default=$$default_ref;
  print "[$default] ";
  $default=<>;
  chop($default);
}    

sub get_data {
  my $target_ref=@_[0];
  my $target=$$target_ref;
  $target=<>;
  chop($target);
}

sub confirm {
  print "[y] ";
  $_=<>;
  if (/n/i) {
    return(0);
  } else {
    return(1);
  }
}

sub say {
  my @words=split('\s', @_[0]);
  my @line, $i, $length=0;
  for ($i=0;$i<=$#words;$i++) {
    $_=$words[$i];
    if (($length+length($_))<80) {
      push(@line, $words[$i]);
    } else {
      print join(' ', @line)."\n";
      @line=($words[$i]);
      $length=0;
    }
    $length+=length($words[$i]);
  }
  print join(' ', @line)."\n";
}

1;

