#!/usr/bin/perl -w

use File::Temp qw/ tempfile tempdir /;

sub usage() {
    print STDERR "cws-extract [-d cvs_root] [-w|--mws mws] cws_name [ouput_filename]
Create a patch from an up-stream CWS suitable for ooo-build.

  -d cvs_root   Specify the CVS root.
  -w|--mws mws  Specify the Master Workspace name (defaults to SRC680)\n";
    exit 1;
}

# parameters
my $cws = shift @ARGV;
my $cvsroot = "";
my $mws = "SRC680";
if (!defined $cws || $cws eq "-h" || $cws eq "--help") {
    usage();
}
if ($cws eq "-d") {
    $cvsroot = shift @ARGV;
    $cws = shift @ARGV;
}
if ($cws eq "-w" || $cws eq "--mws") {
    $mws = shift @ARGV;
    $cws = shift @ARGV;
}
if (!defined $cws || !defined $mws || !defined $cvsroot) {
    usage();
}

my $outfile = shift @ARGV;
if (!defined $outfile) {
    $outfile = "cws-$cws.diff";
}

$ENV{SRC_ROOT} || die "Havn't sourced the environment";

if ( $cvsroot eq "" ) {
    -f "solenv/CVS/Root" || die "Doesn't look like a live OO.o cvs checkout to me";

    $cvsroot = `cat solenv/CVS/Root`;
    $cvsroot =~ s/\n/ /g;
    $cvsroot =~ s/\s*$//;
}

my $ucmws = uc( $mws );
my $modules = `CWS_WORK_STAMP=$cws cwsquery modules -m $ucmws`;
$modules =~ s/\r\n//g;
$modules =~ s/\n/ /g;
$modules =~ s/  / /g;

my @mod_list = split (/ /, $modules);
print STDERR "Modules: '" . join (",", @mod_list) . "'\n";

for my $module (@mod_list) {
    my $tag = "cws_" . lc($mws) . "_$cws";
    my $anchor = uc ("$tag" . "_ANCHOR");

    my $tmp = tempdir ("$tag.XXXXXX", CLEANUP => 1);
    print STDERR "Using temp directory: $tmp\n";

    print STDERR "cvs -d '$cvsroot' checkout -r$tag $module\n";
    system ("cd $tmp && cvs -d '$cvsroot' checkout -r$tag $module\n");
    
    print STDERR "cvs -d '$cvsroot' diff -kk -upN -w -r$anchor -r$tag $module >> $outfile 2>&1\n";
    system ("( cd $tmp && cvs -d '$cvsroot' diff -kk -upN -r$anchor -r$tag $module ) >> $outfile 2>&1");
}
