#!/usr/bin/perl -w

use strict;
use File::Path;

# Java location is needed for ant.
$ENV{JAVA_HOME} = '/usr/java/jdk1.5.0_05';

# URL for the repository and the cache area to use.
my $repos = "http://svn.lal.in2p3.fr/Quattor";
#my $repos = "http://grid05.lal.in2p3.fr/svn/Quattor";
my $cache = "/root/quattor/svncache";

# Name the arguments.  Both must be specified.
my $tag = shift or die "Must supply the tag.\n";

# The location of the directory for checking out the tag.
# It must exist before this script is run. 
die "$cache doesn't exist or isn't a directory.\n" unless (-d $cache);

# Print information. 
print "Processing...\n";
print "Repository: $repos\n";
print "Tag: $tag\n\n";
print "Cache: $cache\n\n";

my $rc = 0;
my $output;
my $cmd;


# Either check out a fresh copy or update an existing one.
# If the svncache directory exists, then we assume there is an existing copy.
# In case of error during switch (3 attempts in case of transient server error),
# delete svncache and do a fresh checkout. 
print "Switching to new tag ($tag)...\n";
if (-d "$cache") {
    my $i = 3;
    while ( $i > 0 ) {
      $output = `svn switch $repos/tags/$tag $cache 2>&1 `;
      $rc = $?;
      $i--;
      if ( $rc ) {
          print "Error during switch. $i attempts remaining...\n";
          sleep 5;
      } else {
          $i = 0;
      }
    };
    
    # In case of error during switch, redo a fresh checkout
    if ( $rc ) {
      print "Error during swith to new tag. Deleting $cache...\n";
      rmtree($cache);
    }
}

if (!-d "$cache") {
    print "Doing a fresh check out of new tag...\n";
    $output = `svn co $repos/tags/$tag $cache 2>&1`;
    $rc = $?;
}
print "$output\n";
if ( $rc ) {
    print "Failed to switch to new tag $tag (SVN status=$rc)\n";
    exit (2);
}

# Go to that location.
chdir $cache;

# Now run the deploy and notify target with ant. 
print "Running ant (deploy.and.notify)...\n";
$cmd = "$cache/external/ant/bin/ant";
if (-x $cmd) {
    $output = `$cmd deploy.and.notify 2>&1`;
    $rc = $?;
} else {
    die "$cmd doesn't exist\n";
}
print "$output\n";

# Ant doesn't always set the exit code correctly.  Check the 
# output of the command as well.
unless ($output =~ m/BUILD SUCCESS/) {
    $rc = 1;
}

# Just indicate that things are ok.
print "Done.\n";

exit($rc);

