#!/usr/bin/perl
# mkftplist.pl
#
# Perl script to generate the Eagles BBS ftplist file.
# Ray Rocker
# Initial revision: June 4, 1994
#
# This program must be run from the bbs home directory if BBSHOME is not
# defined in the environment; it will not complete if the etc/ftplist 
# is not found.
#
# Usage: mkftplist.pl <root-dir>
# Adds an entry for every directory under <root-dir> to the ftplist if one 
# does not exist. The name of the file board defaults to the basename of the 
# directory. Conflicts will be resolved if possible by appending things, 
# and warnings will be generated when this happens.
#

$ftplist = "etc/ftplist";
$oldlist = "etc/ftplist.bak";
$newlist = "etc/ftplist.new";

$argc = @ARGV;
if ($argc < 1) {
  die "Usage: mkftplist.pl <root-dir>";
}
$rootdir = $ARGV[0];

$homedir = $ENV{"BBSHOME"};
if ("$homedir" ne "") {
  chdir($homedir) || die "Cannot chdir to $homedir: $!";
}

open(FTPLIST, "$ftplist") || die "Cannot open $ftplist for reading: $!";
while (<FTPLIST>) {
  if (/^#/ || /^\s/) {
    next;
  }
  ($bname, $bdir, $comment) = split(/:/);
  if (! -d $bdir) {
    print "$bdir is not a directory, removing\n";
  }
  else {
    $ftp{$bdir} = $bname;
    push(@bnames, $bname);
  }
}

&Recurse($rootdir);

seek(FTPLIST, 0, 0) || die "Cannot seek $ftplist to beginning: $!";

open(NEWFTPLIST, ">$newlist") || die "Cannot open $newlist for writing: $!";
while (<FTPLIST>) {
  if (/^#/ || /^\s/) {
    print NEWFTPLIST "$_";
    next;
  }
  ($bname, $bdir, $comment) = split(/:/);
  if ($ftp{$bdir}) {
    print NEWFTPLIST "$_";
    $ftp{$bdir} = "";
  }
}

close(FTPLIST);

while (@pair = each %ftp) {
  if ($pair[1]) {
    print NEWFTPLIST "$pair[1]:$pair[0]:\n";
  }
}

close(NEWFTPLIST);
rename($ftplist, $oldlist) || die "Cannot rename $ftplist to $oldlist: $!\n";
if (!rename($newlist, $ftplist)) {
  print STDERR "Cannot move $newlist to $ftplist: $!\n";
  print STDERR "Leaving old ftplist intact.\n";
  rename($oldlist, $ftplist);
}

sub Recurse {
  local($dir) = $_[0];
  local(*DHANDLE);
  local($fullname);
  local($file);
  
  if (opendir(DHANDLE, $dir)) {
    while ($file = readdir(DHANDLE)) {
      if ($file =~ /^[.]{1,2}$/) {
        next;
      }
      $fullname = "$dir/$file";
      if (! -d $fullname) {
        next;
      }
      &Recurse($fullname);      
      if (!($ftp{$fullname})) {
        &Resolve($file);
        $ftp{$fullname} = $file;
        push(@bnames, $file);
      }
    }      
    closedir(DHANDLE);
  }
}  

sub Resolve {
  local($origfile) = $_[0];
  local($origcopy) = substr($origfile, 0, 12);
  local($tempfile) = $origcopy;
  local($hitcount) = 1;
  while (grep("$tempfile" eq "$_", @bnames)) {
    $tempfile = $origcopy.$hitcount;
    if (length($tempfile) > 12) {
      chop($origcopy);
      $hitcount = 1;
      $tempfile = $origcopy.$hitcount;
    }    
    $hitcount++;
  }
  if ($origfile ne $tempfile) {
    print STDERR "Warning: $fullname is board $tempfile\n";
    $file = $tempfile;
  }
}





