#!/usr/bin/perl -w
#

use strict;

use lib '/app/tools/common/lib';
use Common::SVN::Branch;

use Getopt::Std;
use File::Basename;

my %opt;

usage() unless getopts( 'c:m:b:t:rhd', \%opt );

usage() if ( $opt{h} );

my $svn = new Common::SVN::Branch();

unless ( $svn->login() ) {
    die "Failed to login to SVN\n";
}

my $count = 0;

$count++ if ( $opt{b} );
$count++ if ( $opt{c} );
$count++ if ( $opt{m} );
$count++ if ( $opt{t} );
$count++ if ( $opt{r} );

if ( $count < 1 ) {
    print STDERR "ERROR: -c, -b, -t, -r or -m required\n";
    usage();
}

if ( $count > 1 ) {
    print STDERR "ERROR: -c, -b, -t, -r and -m are mutually exclusive\n";
    usage();
}

if ( $opt{d} ) {
    $ENV{DEV_SERVER} = 1;
}

if ( $opt{c} ) {
    $svn->checkout( $opt{c}, $ARGV[0] );
} elsif ( $opt{b} ) {
    $svn->toBranch( $opt{b} );
} elsif ( $opt{t} ) {
    $svn->toTesting( $opt{t} );
} elsif ( $opt{r} ) {
    $svn->toRelease();
} elsif ( $opt{m} ) {
    $svn->mergeBranch( $opt{m}, $ARGV[0] );
} else {
    die "You should never get here";
}

print "Created SVN branch from '" . $svn->source . "' to '" . $svn->destination . "'\n"
  if ( $svn->source && $svn->destination );

sub usage {
    my $prog = basename $0;

    print <<EofUSAGE;

usage: $prog [-d] -c source [destination]
       $prog [-d] -b branch_name
       $prog [-d] -t source
       $prog [-d] -r
       $prog [-d] -m source_url working_dir
       $prog -h
            -c - checkout 'source' and store it locally in 'destination' (default to current dir)
                   eg. trunk, branches/branch_name, release/release_name
            -b - Branch trunk to 'branch_name'
            -t - Branch 'source' to testing.
                   eg. trunk, branches/branch_name, release/release_name
            -r - Branch testing/trunk to release/YYYYMMDD_RRR
            -m - Merge the trunk or branch to a current working repository.
                   ** the source must be a url and the desitination must be a
                   ** locally checked out repository.
            -d - display debug information to STDERR
            -h - display this screen
EofUSAGE

    exit 1;
}
