#!/usr/athena/bin/perl

$rcp_bin    = '/usr/athena/bin/rcp';
$rsh_bin    = '/usr/athena/bin/rsh';
$serverside = '/afs/sipb.mit.edu/project/www/bin/server.webfile';
$rsh_cmd    = $rsh_bin . ' -x www.mit.edu -l wwwmaint ' . $serverside;

chop($cwd = `pwd`);

@to_process = grep($_ = &filter_files($_), @ARGV);

# 0 implies 1 argument; -1 implies no arguments
if ($#to_process < 0) {
    print "You should supply this program with a list of arguments,\n";
    print "where each argument is a valid filename that should be copied\n";
    print "from /afs/sipb/project/www/root onto the web server.\n\n";
    print "Any element of the filenames you specify can be a symlink;\n";
    print "if the last element is a symlink, it will not be expanded.\n";
    print "(thus, you can run webfile on root/people/foo and it will work)\n";
    print "if you specify a directory, the script will recurse over the\n";
    print "contents of that directory.\n";
    exit(0);
}

system($rsh_cmd  . " " . join(" ", @to_process) . "\n");

sub filter_files {
     local($file) = @_;
     local($newfile);

     $newfile = &expand_file($file);

    if ($newfile !~ /^\/afs\/sipb(\.mit\.edu)?\/project\/www\/root\//) {
	print STDERR "Ignoring " . $file;
	print STDERR " -- not in /afs/sipb/project/www/root\n";
	0;
    } else {
	$newfile =~ /^\/afs\/sipb(\.mit\.edu)?\/project\/www/;
	$';
    }
}

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

   # 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);
}
