#!/usr/bin/perl -w

###############################################################################
# cvsrsync: Copyright (c) 2001 David Sitsky.  All rights reserved.
# sits@users.sourceforge.net
#
# cvsrsync is a perl script which is used for synchronising changes between
# two different branches when it is required that the target branch become
# the same as the source branch.  Its uses rsync to make the target branch
# contain the same contents as the source branch.  It will also adds files
# (using cvs add) that exist in the source branch, but not in the target
# branch.  It will also remove files (using cvs remove) that don't exist
# on the source branch, but exist on tha target branch.
#
# For this script to work, it is required to have checkouted copies of the
# source and target branches.  To run the script, just go:
#
# cd <target-branch-dir>
# cvsrsync.pl <source-branch-dir>
#
# Note this script doesn't use cvs commit at any point.
#
# This program is free software; you can redistribute it and modify it under
# the terms of the GPL.

# Files to be deleted.
@deleted_files = ();

# Files to be added.
@added_files = ();

# Files to be over-written.
@modified_files = ();

if ($#ARGV != 0)
{
    print "cvsrsync v1.0\n";
    print "usage: cvsrsync.pl <source directory>\n";
    exit 1;
}

# The source directory.
$source_directory = $ARGV[0];

# Make sure there is a trailing '/' to $source_directory so that rsync
# does the right thing.
if (! ($source_directory =~ /\/$/))
{
    $source_directory .= "/";
}

open (RSYNC1, "rsync -Cavzn --delete $source_directory ./ |") || die "Unable to run rsync: $!";

while (<RSYNC1>)
{
    if (/^building file list/ ||
	/^wrote .* bytes  read/ ||
	/^total size is/)
    {
	# Ignore these lines
    }
    elsif (/^deleting (.*)$/)
    {
	$deleted_files[++$#deleted_files] = $1;
	print "File $1 is being deleted\n";
    }
    elsif (/^(.*)$/)
    {
	$filename = $1;
	if (-e $filename)
	{
	    # File is being modified.
	    $modified_files[++$#modified_files] = $filename;
	    print "File $filename is being modified\n";
	}
	else
	{
	    # File is being added.
	    $added_files[++$#added_files] = $filename;
	    print "File $filename is being added\n";
	}
    }
}

# Now actually perform the rsync command
`rsync -Cavz --delete $source_directory ./`;

# Now do the appropriate CVS commands for the above files.
for ($i = 0; $i <= $#added_files; $i++)
{
    print "Running cvs add $added_files[$i]\n";
    `cvs add $added_files[$i]`;
}

# Now do a cvs remove for those files removed.
for ($i = 0; $i <= $#deleted_files; $i++)
{
    print "Running cvs remove $deleted_files[$i]\n";
    `cvs remove $deleted_files[$i]`;
}
	
