#!/bin/perl -w
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
use strict;
use Getopt::Long;


# Gets a SNV revision number


my ($opt_nsis, $opt_text);
my $revision;


sub msg($) {
	print STDERR shift;
}

sub error($) {
	msg shift;
	exit 1
}


GetOptions("--nsis" => \$opt_nsis,
	   "--text" => \$opt_text);

my $repository_path = shift @ARGV;
error "Syntax: $0 <repository_path>" unless ( -d "$repository_path" );

my $version_file = "$repository_path/indra/llcommon/llversion.h";
error "$version_file not found" unless (-f $version_file );

msg "Getting SL version number... ";
open(VER, $version_file) or die "Can't open $version_file: $!";

my ($major, $minor, $patch, $build);
while (my $line = <VER>) {
	chomp $line;
	$major = $1 if ( $line =~ /.*?\sLL_VERSION_MAJOR = (\d+);\s*$/ );
	$minor = $1 if ( $line =~ /.*?\sLL_VERSION_MINOR = (\d+);\s*$/ );
	$patch = $1 if ( $line =~ /.*?\sLL_VERSION_PATCH = (\d+);\s*$/ );
	$build = $1 if ( $line =~ /.*?\sLL_VERSION_BUILD = (\d+);\s*$/ );	
}
close(VER);

unless(defined $major && defined $minor && defined $patch && defined $build) {
	error "Failed to parse version number";
}

msg "$major.$minor.$patch.$build\n";

if ( $opt_nsis ) {
	msg "Getting revision number... ";
	$revision=`svnversion "$repository_path"`;
	chomp $revision;
	$revision =~ s/[A-Za-z]//g;
	msg "$revision\n";
}

#print "!define REVISION \"$revision\"" > revision.nsh

if ( $opt_nsis ) {
print <<VERSIONH;
; Automatically generated by gen_revision.pl
; do not edit, changes will be lost.

!ifndef _VERSION_NSH_
!define _VERSION_NSH_

!define SVN_REVISION "$revision"

!define SL_VERSION_MAJOR "$major"
!define SL_VERSION_MINOR "$minor"
!define SL_VERSION_PATCH "$patch"
!define SL_VERSION_BUILD "$build"
!define SL_VERSION "\${SL_VERSION_MAJOR}.\${SL_VERSION_MINOR}.\${SL_VERSION_PATCH}.\${SL_VERSION_BUILD}"

!endif
VERSIONH
} elsif ( $opt_text ) {
	print "${major}.${minor}.${patch}.${build}"
}

