#!/usr/bin/perl -w
# $Date: 2008/03/17 07:54:16 $

# help merging what cvsq-branch brought apart

use strict;
use Cwd;
use Getopt::Long qw(:config require_order);


my $home=$ENV{'HOME'};
defined $home && -d $home
	or die "Invalid home directory.\n";


my $pwd = getcwd();

## Ensure, all the needed directories are present.

foreach my $dir (qw! .cvsq-branch .cvsq-branch/merge !) {
     -d "$home/$dir" and next;
     mkdir "$home/$dir", 0700
         or die "Unable to create directory `$home/$dir' ($!)\n";
 }

## Options

my $cvs = "cvs";

GetOptions(
    'l' => sub {$cvs = "lcvs do-local"},
);


## Our single argument is ".<tag>", where tag is the tag of the branch to be merged in

@ARGV == 1 or die "usage $0 .<tag>\n";

$ARGV[0] =~/^\.(.*)/ or die "First argument has to be a dot, followed by the branch tag";

my $tag = $1;

print "Preparing a merge for the branch >$tag<\n";


## set up the directories

system "rm", "-rf", "$home/.cvsq-branch/merge/$tag"
	and die "Couldn't remove old merging point ($?)\n";

mkdir "$home/.cvsq-branch/merge/$tag", 0700
         or die "Unable to create directory `$home/.cvsq-branch/merge/$tag' ($!)\n";

system "cp", "-r", "$pwd", "$home/.cvsq-branch/merge/$tag/origin"
	and die "copying failed ($?)\n";

system "cp", "-r", "$pwd", "$home/.cvsq-branch/merge/$tag/branch"
	and die "copying failed ($?)\n";

print "(cd \Q$home\E/.cvsq-branch/merge/$tag/origin; $cvs update -r$tag-start)\n";
system "(cd \Q$home\E/.cvsq-branch/merge/$tag/origin; $cvs update -r$tag-start)"
	and die "command failed ($?)\n";

print "(cd \Q$home\E/.cvsq-branch/merge/$tag/branch; $cvs update -r$tag)\n";
system "(cd \Q$home\E/.cvsq-branch/merge/$tag/branch; $cvs update -r$tag)"
	and die "command failed ($?)\n";

## create symbolic links to make accessing these directories easier

print "\n\nThe origin of the branch $tag is in directory $home/.cvsq-branch/merge/$tag/origin\n";
print "The end of the branch $tag is in directory $home/.cvsq-branch/merge/$tag/branch\n";
print "Will create symbolic links .origin and .branch to help accessing these directories\n";

system "ln", "-s", "$home/.cvsq-branch/merge/$tag/origin", "$pwd/.origin"
	and print "Warning couldn't create link .origin ($?)\n";

system "ln", "-s", "$home/.cvsq-branch/merge/$tag/branch", "$pwd/.branch"
	and print "Warning couldn't create link .branch ($?)\n";


