#!/usr/bin/perl
#
# ORXONOX nightly Revision Making utility
# for WINDOWS binaries


# DEFINITIONS
my $BinaryRepository = "http://svn.orxonox.net/webdev/develop/win32/binary";
my $RuntimeRepository = "http://svn.orxonox.net/webdev/develop/win32/runtime";
my $DataRepository = "http://svn.orxonox.net/data/trunk";
my $ReleaseDir = "/var/www/orxonox/files/snapshots";
my $tmpDir = "/tmp/revmakeWin";


# USED IN THIS SCRIPT
my $BinaryLastChangedVersion  = 0;
my $RuntimeLastChangedVersion = 0;
my $DataLastChangedVersion    = 0;
my $doUpdate                  = 0;
my $orxonoxVersion            = "";


##Function Stack ##
prepareEnvironment();
checkVersion();
checkChanges();
if ($doUpdate == 0) { 
  die "Nothing to do. Already at newest Version\n"; }
gatherData();

exportToRelease();
compress();
moveToReleaseDir();

sendMail();
writeVersion();
###################

#################################################################
# Creates a Temporary Directory for the Data                    #
#################################################################
sub prepareEnvironment()
{
  print "Preparing Environment\n";
  if (!-e $tmpDir){
   mkdir("$tmpDir");
  }
  if(!-e "$tmpDir/checkout"){
   mkdir("$tmpDir/checkout");
  }
  
  print "removing old versions\n";
  system("rm -rf $tmpDir/orxonox");
  mkdir("$tmpDir/orxonox");
}

#################################################################
# Checks the Runtime and Data Repository for the Version Number #
#################################################################
sub checkChanges()
{
  my $binRev         = 0;
  my $runtimeRev     = 0;

  ## reading the Old Revisions
  open (LASTVERSIONS, "$tmpDir/.lastVersions");
  while ($line = <LASTVERSIONS>)
  {
    if ($line =~ s/^bin: ([1234567890]*)$/\1/) {
      $binRev = $line;
      chomp($binRev);
    }
    elsif ($line =~ s/^runtime: ([1234567890]*)$/\1/) {
      $runtimeRev = $line;
      chomp($runtimeRev);
    }
  }
  close (LASTVERSIONS);
  

  $BinaryLastChangedRevision = getRevisionNumber($BinaryRepository);
  if ($BinaryLastChangedRevision > $binRev) {
    $doUpdate = 1;
    print "located new Binary-Revision Number $BinaryLastChangedRevision\n";
  }

  $RuntimeLastChangedRevision = getRevisionNumber($RuntimeRepository);
  if ($RuntimeLastChangedRevision > $runtimeRev) {
    $doUpdate = 1;
    print "located new Runtime-Revision Number $RuntimeLastChangedRevision\n";
  }

  return ($doUpdate);
}

################################################################
# get last changed Revision Number (used by getRevisions())    #
################################################################
sub getRevisionNumber()
{
  my $repository = $_[0];
  my $retval = 0;
  open ( LOG, "svn log $repository --limit 1 |") or return $retval;
  while ($line = <LOG>)
  {
    if ($line =~ s/^r([1234567890]*).*/\1/)
    {
        $retval = $line;
	chomp $retval; 
        break;
    }
  }
  close ( LOG );
  return $retval;
}


################################################################
# 
################################################################
sub gatherData()
{
  checkoutRepos($DataRepository, "$tmpDir/checkout/data");
  checkoutRepos($RuntimeRepository, "$tmpDir/checkout/runtime");
  checkoutRepos($BinaryRepository, "$tmpDir/checkout/binary");
}

################################################################
# Checks out a repository from $_[1] to $_[2]                  #
# also makes some test, if the local Version is locked...      #
################################################################
sub checkoutRepos()
{
  my $repos = $_[0];
  my $destination = $_[1];
  my $CHECKOUT;
  my $line;
  my $done = 0;

  while ($done == 0)
  {
    open(CHECKOUT, "svn co $repos $destination 2>&1 |");
    while ($line = <CHECKOUT>)
    {
      $done = 1;
      print("$line");
      if ($line =~ /^svn:.* locked/)
      {
      	print "cleaning up $destination\n"; 
        system("svn cleanup $destination");
        $done = 0;
	break;
      }
    }
    close ( CHECKOUT );
  }
}

##############################################################
# Checks the Version of orxonox and also if the file exists  #
##############################################################
sub checkVersion()
{
  if (!-e "$tmpDir/checkout/binary/orxonox_version") {
    $doUpdate = 1;
    return; }
  open(ORXVERSION, "svn cat $BinaryRepository/orxonox_version |");
  while ($line = <ORXVERSION>)
  {
    if ($line =~ s/^orxonox_version: (.*)/\1/) {
      $orxonoxVersion = $line;
      chomp($orxonoxVersion);
    }
  }
  close (ORXVERSION);
  if ($orxonoxVersion ne "") {
    print ("new Version will be $orxonoxVersion\n");
  }
  else {
    die ("ORXONOX VERSION NOT FOUND IN $tmpDir/checkout/binary/orxonox_version\n");
  }

  if (!-e "$ReleaseDir/orxonox-$orxonoxVersion-win32.zip") {
    $doUpdate = 1;
  }
}

#############################################################
# RELEASE CREATION
#############################################################
sub exportToRelease()
{
  system("svn export $tmpDir/checkout/data $tmpDir/orxonox/data --force");
  system("svn export $tmpDir/checkout/runtime $tmpDir/orxonox/ --force");
  system("svn export $tmpDir/checkout/binary $tmpDir/orxonox/ --force");
}


sub compress ()
{
  chdir($tmpDir);
   print("creating ZIP file\n");
   open(ZIP, "zip -r -9 orxonox.zip orxonox |");
   while($line = <ZIP>)
   {
      print("$line");
   }
   close ( ZIP );
}

sub moveToReleaseDir()
{
  system("mv $tmpDir/orxonox.zip $ReleaseDir/orxonox-$orxonoxVersion-win32.zip");
  if (-e "$ReleaseDir/orxonox-win32-latest.zip") {
    system("rm $ReleaseDir/orxonox-win32-latest.zip"); }
  system("ln -s orxonox-$orxonoxVersion-win32.zip $ReleaseDir/orxonox-win32-latest.zip")
}



sub sendMail()
{
  my $sendmail = "/usr/sbin/sendmail -t";
  my $reply_to = "Reply-to: orxonox-dev\@mail.datacore.ch\n";
  my $subject  = "Subject: new orxonox-win32-binary generated: Version: $orxonoxVersion\n";
  my $from     = "From: orxonox\@orxonox.ethz.ch\n";
  my $to       = "orxonox\@orxonox.ethz.ch\n";
  my $sendTo   = "To: orxonox-commit\@mail.datacore.ch\n";
  my $content  = "A new binary version of orxonox for Windows has arrived: Version: $orxonoxVersion\n" .
		 "------------------------------------------------------------------------------------\n\n" .
                 "You can download it from: \n" .
                 "  http://www.orxonox.net/files/snapshots/orxonox-$orxonoxVersion-win32.zip\n" .
		 "or the always valid substitution Link:\n" .
		 "  http://www.orxonox.net/files/snapshots/orxonox-win32-latest.zip\n" .
		 " \n\n" .
		 "# # This is an automated Mail generated by the RevisionMaker # #\n" .
		 " #   Please report missing links to orxonox-dev\@mail.datacore.ch   #\n"  .
		 ".\n";
 
  open( SENDMAIL, "| $sendmail") or die "Cannot open $sendmail: $!";
  print SENDMAIL $sendTo;
  print SENDMAIL $from;
  print SENDMAIL $subject;
  print SENDMAIL $reply_to;
  print SENDMAIL "Content-type: text/plain\n\n";
  print SENDMAIL $content;
  close(SENDMAIL);  
}



###############################################################
# Writes out the Last Known Version to a log-file             #
###############################################################
sub writeVersion()
{
  open(LASTVERSIONS, "> $tmpDir/.lastVersions");
  print LASTVERSIONS ("## DO NOT CHANGE THIS FILE ##\n");
  print LASTVERSIONS ("bin: $BinaryLastChangedRevision\n");
  print LASTVERSIONS ("runtime: $RuntimeLastChangedRevision\n");
  print LASTVERSIONS ("data: $DataLastChangedRevision\n");
  print LASTVERSIONS ("#EOF");
  close ( LASTVERSION );
}



