#!/usr/bin/perl -w

sub scan_dirs($$);

sub rewrite_cvs($$)
{
    my $dir_path = shift;
    my $new_root = shift;

    -d $dir_path || return;

    printf "Re-write root $dir_path\n";
    my $file;
    my $file_name = "$dir_path/Root";
    if (open ($file, ">$file_name") ) {
	print $file "$new_root\n";
	close $file;
    } else {
	print "Couldn't open '$file_name': $!\n";
    }

    return;

# speculative - as I recall the internal repository path is different too
    my $src;
    my $src_name = "$dir_path/Repository";
    if (open ($src, $src_name)) {
	my $dest;
	my $dest_name = "$src_name.tmp";
	open ($dest, ">$dest_name") || die "Can't open $dest_name for writing: $!";
	while (<$src>) {
	    s/^foo\///;
	    print $dest $_;
	}
	close ($src) || die "can't close $src_file: $!";
	close ($dest) || die "can't close $dest_file: $!";
	rename $dest_file, $src_file || die "Can't rename $src_file to $dest_file: $!";
    }
}

sub scan_dirs($$)
{
    my $dir_path = shift;
    my $new_root = shift;

    my $misc_dir;
    opendir ($misc_dir, $dir_path) || return;
    my $name;
    while ($name = readdir ($misc_dir)) {
	$name =~ /^\./ && next;
	-d "$dir_path/$name/CVS" && scan_dirs ("$dir_path/$name", $new_root);
    }
    closedir ($misc_dir);
    rewrite_cvs ("$dir_path/CVS", $new_root);
}

# main
my $cvsPath;
chomp ($pwd = `pwd`);

if (!($cvsPath = shift @ARGV)) {
    print "Syntax: re-root <path-of-checkout> [<new root>]\n";
    exit 1;
}
if ($cvsPath =~ /^\./) {
    $cvsPath = $pwd . "/$cvsPath";
}

my $newRoot;
if (!($newRoot = shift @ARGV)) {
    $newRoot = ':pserver:anoncvs@anoncvs.services.openoffice.org:/cvs';
}

print "Path: $cvsPath\n";

scan_dirs ($cvsPath, $newRoot);
