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

($Distdir, $Basedir, $Tmpdir, $Htmlprefix, $Cgidir, $Cgiprefix, $RealOS, $RealOSVer,
$AllowCmd, $FontSize, $BaseLink, $MimeFile, $NoCookie, $AllowUpload, $DirCpCmd) = @ARGV;
$Basedir = "" if $Basedir eq "/";
$OrigPref = $Distdir."/preferences.orig";
$NewPref  = $Cgidir."/fm_preferences.pl";
$RealOs = "Unix" unless $RealOS;
$NoCookie = "" unless $NoCookie eq "y";
$DirCpCmd =~ s/ //g;

# Read original file
open(IN, "<$OrigPref") || die "Unable to find the preferences file.";
@lines = <IN>;
close(IN);

# Replace updates
open(OUT, ">$NewPref") || die "Unable to update the preferences file";
foreach $line (@lines) {
  if    ($line =~ /^\s*\$Basedir\s*=/)     { print OUT "\$Basedir       = \"",$Basedir,    "\";\n"; }
  elsif ($line =~ /^\s*\$BaseLink\s*=/)    { print OUT "\$BaseLink      = \"",$BaseLink,   "\";\n"; }
  elsif ($line =~ /^\s*\$AllowCmd\s*=/)    { print OUT "\$AllowCmd      = \"",$AllowCmd,   "\";\n"; }
  elsif ($line =~ /^\s*\$AllowUpload\s*=/) { print OUT "\$AllowUpload   = \"",$AllowUpload,"\";\n"; }
  elsif ($line =~ /^\s*\$DirCpCmd\s*=/)    { print OUT "\$DirCpCmd      = \"",$DirCpCmd,   "\";\n"; }
  elsif ($line =~ /^\s*\$FontSize\s*=/)    { print OUT "\$FontSize      = \"",$FontSize,   "\";\n"; }
  elsif ($line =~ /^\s*\$Htmlprefix\s*=/)  { print OUT "\$Htmlprefix    = \"",$Htmlprefix, "\";\n"; }
  elsif ($line =~ /^\s*\$Cgidir\s*=/)      { print OUT "\$Cgidir        = \"",$Cgidir,     "\";\n"; }
  elsif ($line =~ /^\s*\$Cgiprefix\s*=/)   { print OUT "\$Cgiprefix     = \"",$Cgiprefix,  "\";\n"; }
  elsif ($line =~ /^\s*\$Tmpdir\s*=/)      { print OUT "\$Tmpdir        = \"",$Tmpdir,     "\";\n"; }
  elsif ($line =~ /^\s*\$MimeFile\s*=/)    { print OUT "\$MimeFile      = \"",$MimeFile,   "\";\n"; }
  elsif ($line =~ /^\s*\$NoCookie\s*=/)    { print OUT "\$NoCookie      = \"",$NoCookie,   "\";\n"; }
  elsif ($line =~ /^\s*\$RealOS\s*=/)      { print OUT "\$RealOS        = \"",$RealOS,     "\";\n"; }
  elsif ($line =~ /^\s*\$RealOSVer\s*=/)   { print OUT "\$RealOSVer     = \"",$RealOSVer,  "\";\n"; }
  else                                     { print OUT $line; }
}
close(OUT);

# Read new file
open(IN, "<$NewPref") || die "Unable to find the preferences file: $NewPref";
@lines = <IN>;
close(IN);

# Eval each appropriate item
open(F, ">$NewPref") || die "Unable to update preferences file: $NewPref";
$inauto = 1;
foreach $line (@lines) {
  chomp $line;
  $inauto = 0 if $line =~ /# -- END AUTO PREFERENCES/;
  if ($inauto && ($line =~ /^\$/)) {
    eval($line);
    ($arg, $val) = $line =~ /^.([^ =]+)\s*=\s*(.+)\s*;$/;
    $val = eval($val);
    $val =~ s/\@/\\\@/g;
    print F "\$".$arg." = \"".$val."\";\n";
  } else {
    print F $line,"\n";
  }
}
close(F);

exit 0;
