#!/usr/bin/perl -w

# CVS/Root CVS/Repository ajusting
# <a href="mailto:leandro@ibnetwork.com.br">Leandro Rodrigo Saad Cruz</a>
# 2003-06-12


use strict;

#
# Replaces the CVS/Root file 
#
sub replaceRoot
{
    print "$_[0]/Root\n";
    open(ROOT,">$_[0]/Root");
    print ROOT $_[1];
    close(ROOT);
}

#
# Replaces CVS/Repository file
#
sub replaceRepo
{
    print "$_[0]/Repository\n";
    open(REPO,">$_[0]/Repository");
    print REPO $_[1];
    close(REPO);

}

#
# Main routine
#
sub search
{
    my ($file, $option, $value, $root, $pathname,@filenames);

    $root = $_[0];
    $option = $_[1];
    $value = $_[2];
    
#   print "[DEBUG] Root :$root , option $option\n";
    opendir(ROOT,$root) || die "Can´ t open $root : $!";
    
    @filenames = readdir(ROOT);
    close(ROOT);
    foreach $file (@filenames)
    {
	$pathname = $root."/".$file;
	
	if (-d $pathname && !($file =~ /\./) && !($file =~/\../))
	{
	    search($pathname,$option,$value);
	}
	if(-d $pathname && $file =~ /CVS/)
	{
	    if("--root" eq $option)
	    {
		replaceRoot($pathname,$value);
	    }
	    elsif("--repo" eq $option)
	    {
		replaceRepo($pathname,$value);
	    }
	    else
	    {
		print "No suitable option[$option]. Exiting...\n";
		exit(1);
	    }
	}
    }
}      

if(@ARGV < 3)
{
    print "Usage: chcvs.pl [--root|--repo] DIRNAME NEW-ROOT|NEW-REPO\n";
    print "Example: chcvs.pl --root xingu ':pserver:leandro\@cvs.ibnetwork:/home/cvs'\n";
    print "Example: chcvs.pl --repo xingu new-repo-name \n";
    exit(1);
}

# print "Running with dir:$ARGV[1], option:$ARGV[0], value:$ARGV[2]\n";

search($ARGV[1], $ARGV[0], $ARGV[2]);
