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

$gcp_bin = '/usr/local/bin/gcp';
$error_log_file = '/tmp/webfile.errors';
$AFS_www_dir   = '/afs/sipb.mit.edu/project/www';

# 0 implies 1 argument; -1 implies no arguments
if ($#ARGV < 0) {
    print "No arguments supplied. You must be a moron.\n";
}

umask(002);
chdir $AFS_www_dir;
unlink($error_log_file);

grep(&main($_), @ARGV);

unlink($error_log_file);

sub main {
    local($newfile, $afsfile, $localdir, $localfile, @updated,
	  $localdirtree) = $_;
    $afsfile   = $newfile;
    $localdir  = "/var/local/www";
    $localfile = $localdir . $newfile;
    @updated = ();

    $afsfile =~ s/^\/*//;

    $localdirtree = $localfile;
    
    lstat ($AFS_www_dir . $newfile);
    if (-d _) {
	# if $newfile is a directory, frob things so gcp DTRT.
	# $localfile =~ s/\/[^\/]+\/?$//;
	# $afsfile = $afsfile . "/";
	$localdirtree =~ s#([^/])/*$#$1/#;
    } else {
	# if $newfile is *not* a directory, do this:
	$localdirtree =~ s/\/[^\/]*$/\//;
    }
	
    open(GCP, ($gcp_bin . " -dfPRruv " . $afsfile . " " . $localdir .
	       " 2>" . $error_log_file . " |"));

    # Grab the names of the files that gcp (tries to) update
    while (<GCP>) {
	/\-\> (.*)$/;
	push(@updated, $1);
    }

    close GCP;
    # this is necessary to fix the permissions on directories which are
    # modified as a side effect of the invocation of gcp. Sigh. I'd rather
    # do this than rewrite gcp.
    @dirstofix = &fixdir($localdirtree);
    @dirstofix = grep($_ ne "", @dirstofix);
    chmod(02775, @dirstofix);

    # next, we make sure everything we copy is world readable, since
    # the webserver won't be able to serve it otherwise.  this only deals
    # with plain files, we handle directories above and don't want to
    # touch symlinks (gemery)
    chmod(0644, grep(-f $_, @updated));

    # If anything was updated, log it.
    if ($#updated > -1) {
	print "WWW: updated file ";
	print join("\nWWW: updated file ", @updated) . "\n";
    }

    # This tests the size of the file. If it's == 0, it will be false.
    # Otherwise, it will be true. If it's true, there were errors logged, and
    # they should be reported.
    if (-s $error_log_file) {

	print "WWW: ERRORS ENCOUNTERED :\n";

	open(ERRLOG, "<" . $error_log_file);
	while (<ERRLOG>) {
	    print $_;
	}
	close(ERRLOG);

    }
    
    unlink($error_log_file);

}

sub fixdir {
    local($dirname, $temp) = @_;

    return "" if ($dirname !~ /^\/var\/local\/www\/root\//) ;

    $dirname =~ s/\/$//;

    $dirname =~ /^(.*\/)[^\/]+$/;
    $temp = $1;

    if ($dirname eq $temp) {
	# This is a loop of recursion. Don't pursue it. :-)
	print "Found infinite recursion on $dirname. Send mail to nocturne.\n";
	return "";
    }

    #recurse!
    return ($dirname, &fixdir($temp));
}
