#!/usr/bin/perl

use Fcntl ':mode';

if (scalar(@ARGV) == 0) {
    print "usage: $0 top_directory [top_directory .. ]\n";
    print "\tThis programs replaces the information in the Root files in a\n";
    print "\tlocal cvs repository with what is currently in your CVSROOT\n";
    print "\tenvironment variable.\n";
    print "\tYour current CVSROOT is $ENV{CVSROOT}\n";
    exit(0);
}
	   
foreach $dir (@ARGV) {
    do_dir($dir);
}

exit(0);

sub do_dir {
    my $prefix = shift;

    return if $prefix eq "CVS"; 
    return if $prefix =~ /\/CVS$/;

    print "Working on Directory: $prefix\n";    

    opendir (DIR, $prefix) or do {
	print "Couldn't open $prefix : $! : skipping\n";
	return;
    };
    my @files = grep !/^\.\.?$/, readdir DIR;
    closedir DIR;
    if ( -e $prefix."/CVS/Root") { # it exists, nuke it
	if (!open(CVS, ">${prefix}/CVS/Root")) {
	    print "Couldn't open ${prefix}/CVS/Root : $!\n";
	} else {
	    print CVS "$ENV{CVSROOT}\n";
	    close CVS;
	}
    }
    my $file;
    foreach $file (@files) {
	next if $file eq "CVS";
	my $path = join("/", $prefix, $file);

	my $type = (lstat($path))[2];
	next if S_ISLNK($type);

	if ( -d $path ) {
	    do_dir($path);
	}
    }
}
