#!/afs/athena/contrib/perl/perl5
#
# Replaces http://fishwrap.mit.edu with http://hacks.mit.edu 
# in a tree of files without changing file modification time.
#
# Usage:  copyacls.pl basedir
#

use File::Find;

$File::Find::dont_use_nlink = 1;

$basedir;

sub do_replace {
    my ($file) = @_;

    if (-l $file) { print "*** do_replace: passed a symlink!\n"; return 0; }
    my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, 
     $atime, $mtime, $ctime, $blksize, $blocks) = stat $file;
    $tmpfile = $file.".tmpMAGIC478935";
    rename $file, $tmpfile;
    open FIN, "<$tmpfile" or do { 
	print "*** do_replace: couldn't open $tmpfile\n"; 
	rename $tmpfile, $file; 
	return 0;
    };
    open FOUT, ">$file" or do { 
	print "*** do_replace: couldn't open output file $file\n"; 
	rename $tmpfile, $file; 
	return 0; 
    };
    foreach $curline (<FIN>) {
	$curline =~ s|cgiecho/afs/fishwrap.mit.edu/Hacks/Gallery/misc|cgiecho/afs/sipb.mit.edu/contrib/hacks/Hacks/misc|g;
	$curline =~ s|cgiemail/afs/fishwrap.mit.edu/Hacks/Gallery/misc|cgiemail/afs/sipb.mit.edu/contrib/hacks/Hacks/misc|g;
	#if ($curline =~ m|fishwrap.mit.edu/afs|) {
	#    print "*** found fishwrap.mit.edu/afs reference in $file\n";
	#} 
	#if ($curline =~ m|/afs/fishwrap.mit.edu|) {
	#    print "*** found /afs/fishwrap.mit.edu reference in $file\n";
	#} 
	#if ($curline =~ m|http://fishwrap.mit.edu|) {
	#    print "*** found http://fishwrap.mit.edu reference in $file\n";
	#} 

	print FOUT $curline;
    }

    close FIN; close FOUT;
    unlink $tmpfile;
    utime $atime, $mtime, $file;
    #chmod $mode, $file;
    chown $uid, $gid, $file;

    return 1;
}

sub print_usage {
    print "Usage:  $0 basedir\n";
    exit -1;
}

sub dir_action {
    #print "trying $File::Find::name\n";
    my $skipit=0;
    $skipit=1 if (! -f $_);
    $skipit=1 if (-l $_);
    $skipit=1 if (!(/\.html$/ || /\.htm$/));
    return if $skipit;
    print "changing base for $File::Find::name\n";
    do_replace $File::Find::name;
}

$basedir    = $ARGV[0] || print_usage;

find (\&dir_action, $basedir);

#do_replace($basedir);
