# updpref.pl
# This script gets run only from setup in order to replace  
# some of the key parameters in the preferences file

($Instdir, $Basedir, $Configdir, $Vardir, $Nmapcmd, $Traceroutecmd, $Autointerval, $DEMO, $Email, $Host, $Port, $SSL) = @ARGV;

open(IN, "<$Instdir/preferences.pl") || die "Unable to find the preferences file.";
@lines = <IN>;
close(IN);

@default = @lines;

if (-f "$Instdir/preferences.old") {
  open(IN, "<$Instdir/preferences.old");
  @old = <IN>;
  close(IN);
  $e = join("\n",@old);
  eval($e);
  for ($i=0;$i<=$#lines;$i++) {
    $line = $lines[$i];
    chomp $line;
    last if $line =~ /END AUTO PREFERENCES/;
    if ($line =~ /^\s*\$[A-Za-z0-9_-]+\s*=.*$/) {
      ($arg,$val) = $line =~ /^\s*\$([A-Za-z0-9_-]+)\s*=(.*)$/;
      if (defined(${$arg})) {
        $lines[$i] = "\$".$arg.' = "'.${$arg}.'";'."\n";
      }
    }
  }
}
$Email =~ s/\@/\\\@/g;

&WriteFile("$Instdir/preferences.def",@default);
&WriteFile("$Instdir/preferences.pl",@lines);
exit 0;

sub WriteFile {
  my $file = shift;
  my @lines = @_;
  my $line;

  open(OUT, ">$file") || die "Unable to update the preferences file";
  foreach $line (@lines) {
    if    ($line =~ /^\s*\$Basedir\s*=/)       { print OUT "\$Basedir       = \"",$Basedir,      "\";\n"; }
    elsif ($line =~ /^\s*\$Configdir\s*=/)     { print OUT "\$Configdir     = \"",$Configdir,    "\";\n"; }
    elsif ($line =~ /^\s*\$Vardir\s*=/)        { print OUT "\$Vardir        = \"",$Vardir,       "\";\n"; }
    elsif ($line =~ /^\s*\$Nmapcmd\s*=/)       { print OUT "\$Nmapcmd       = \"",$Nmapcmd,      "\";\n"; }
    elsif ($line =~ /^\s*\$Traceroutecmd\s*=/) { print OUT "\$Traceroutecmd = \"",$Traceroutecmd,"\";\n"; }
    elsif ($line =~ /^\s*\$Htmldir\s*=/)       { print OUT "\$Htmldir       = \"",$Instdir,      "\";\n"; }
    elsif ($line =~ /^\s*\$Cgidir\s*=/)        { print OUT "\$Cgidir        = \"",$Instdir,      "\";\n"; }
    elsif ($line =~ /^\s*\$Autointerval\s*=/)  { print OUT "\$Autointerval  = \"",$Autointerval, "\";\n"; }
    elsif ($line =~ /^\s*\$DEMO\s*=/)          { print OUT "\$DEMO          = ",  $DEMO,           ";\n"; }
    elsif ($line =~ /^\s*\$Email\s*=/)         { print OUT "\$Email         = \"",$Email,        "\";\n"; }
    elsif ($line =~ /^\s*\$HTTP\s*=/)          { print OUT "\$HTTP          = \"http",($SSL?"s":""),"://",$Host,':',$Port,"\";\n"; }
    else                                       { print OUT $line; }
  }
  close(OUT);
}
