#!/afs/athena/contrib/perl/p

unshift (@INC, '/afs/sipb.mit.edu/project/www/src/db');
require 'dbparse.pl';
# require '/afs/sipb.mit.edu/project/www/bin/homelib.pl';

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

$master_db_file = $DB'default_home;
$newfile  = "/tmp/home.DATA";
unlink($newfile);
system("cp $master_db_file $newfile");
chmod(0666, $newfile);

open(STDERR, ">&STDOUT");
select(STDERR); $| = 1;
select(STDOUT); $| = 1;


if (&DB'ParseHome($newfile) == 0) {
   print "Cannot open $newfile. Aborting.\n";
   exit(0);
}

foreach $user (sort keys %DB'index) {
    ($url, $name, $sort_index, $link, $date) = &DB'FetchUser($user); #'
    if ($url =~ /^\/people\/([^\/]+)\//) {
        $usename = $1;
        if ($link eq "") {
	    $link = readlink(("/afs/sipb/project/www/root/people/".$usename));
	    $link = &expand_file($link);
	    $link =~ s/([^\/])\/*$/$1/;
	    print (" Using: " . $link . "\n");
            &DB'AddUser($user, $url, $name, $sort_index, $link, $date);
        }
    }	
}

if (&DB'SpewHome($newfile) == 0) {
    print "Cannot write $newfile. Aborting.\n";
    print "The database file may be in an inconsistent state. Beware.\n";
    exit(0); 
}

sub expand_file {
   local($file) = @_;
   local($deepest);

   print "Expand: $file\n";

   # If they didn't give an absolute path, tack on the cwd for them.
   if ($file !~ /^\//) {
       $file = ($cwd . "/" . $file);
   }

   $file =~ /^(.*)\/([^\/]*)$/;
   $deepest = $1;
   $file = $2;

   if (-d $deepest) {
       $deepest = `cd $deepest ; /bin/pwd`;
       chop($deepest);
       $file = ($deepest . "/" . $file);
   } else {
       print "$deepest is not a directory. Not pursuing it.\n";
       $file = "";
   }

   return($file);
}
