#!/usr/bin/perl

# Generation of version.info file

# 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 2 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 warnings;

my $name_chars = qr/[-+0-9a-z.]/i;
our $regex_header = qr/^(szarp) \(([^\(\) \t]+)\)((?:\s+$name_chars+)+)\;(.*?)\s*$/i;
our $regex_trailer = qr/^ \-\- (.*) <(.*)>(  ?)((\w+\,\s*)?\d{1,2}\s+\w+\s+\d{4}\s+\d{1,2}:\d\d:\d\d\s+[-+]\d{4}(\s+\([^\\\(\)]\))?)\s*$/o;

my $version_only = 0;
my $path = "";

for (@ARGV) {
	if ($_ eq '-v') {
		$version_only = 1;
	}
	else {
		$path = $_;
	}
}

die "Path to changelog needed" if ($path eq "");

my $version = 'unknown';
my $date = 'unknown';

open (CHANGELOG, $path) or die "Cannot open  changelog";

my $found = 0;

while (<CHANGELOG>) {
	if ($_ =~ $regex_header) {
	    last if $found == 1;
	    $found = 1;
	    $version  = $2;
	    next;
	}
	if ($_ =~ $regex_trailer) {
	    $date = $4;
	    next;
	}
}
close(CHANGELOG);

if ($version =~ /(\d+\.\d+\.\d+)(-.*)/) {
    $version = $1;
}

if ($version_only) {
       print $version;
}
else {
	print "$version $date";
}

