#!/usr/local/bin/perl
$debug = 0;

open META_IN, "META.in" or die "$!";
open META, ">META" or die "$!";

$SIG{__DIE__} = sub { unlink "META" };

while(<META_IN>) {
    chomp;
    if (/^\@/) {
	/^[\@]([\w\d]+)=(..*)$/ or die "invalid spec";
	if ($1 eq 'version') {
	    $version = $2;
	} else {
	    warn "unknown key $1";
	}
    } else {
	if (/\@\@VERSION\@\@/) {
	    $_ = $` . &calculate_version() . $';
	}
	print META "$_\n";
    }
}
close META_IN;
exit 0;

sub calculate_version {
    return $revision if (defined $revision);
    return $version unless (-d '.svn');
    @files = &read_makefile();
    print STDERR "files=", join(" ", @files), "\n" if $debug;
    $cmdline = "svn status -v " . join(" ", @files);
    print STDERR "cmdline=$cmdline\n" if $debug;
    open (STAT, "$cmdline |") or die "$!";
    $maxv = 0;
    while(<STAT>) {
	print STDERR "$_" if $debug;
	chomp;
	warn "no revision file: $!", next if /^\?/;
	/^(.....) +\d+ +(\d+) +[^ ]+ +([^ ]+)$/ or (warn "cannot parse: $_", next);
	$v = $2 + ($1 eq '     ' ? 0.0 : 0.5);
	$maxv = $v if $maxv < $v;
	print STDERR "$3: rev $v maxv $maxv\n" if $debug;
    }
    close STAT;
    die "sub process failed ($?)" if $?;
    die "cannot find revision" unless $maxv;
    $maxv =~ s/\.\d+$/+1/;
    $revision = "$version+svn.$maxv";
    printf STDERR "revision $revision\n" if $debug;
    return $revision;
}

sub read_makefile {
    open (MAKEFILE, "Makefile") or die "cannot open Makefile: $!";
    while (<MAKEFILE>) {
	chomp;
	if (/^SOURCES\s+=\s+(.+)$/) {
	    $sources = $1;
	    while ($sources =~ /^(.+)\\$/) {
		$sources = "$1 ";
		$sources .= <MAKEFILE>;
	    }
	    print STDERR "SOURCES line found: $sources" if $debug;
	} elsif (/^ADDITIONAL_SOURCES\s+=\s+(..*)$/) {
	    $addsources = $1;
	    while ($addsources =~ /^(.+)\\$/) {
		$addsources = "$1 ";
		$addsources .= <MAKEFILE>;
	    }
	    print STDERR "ADDITIONAL_SOURCES line found: $addsources" if $debug;
	}
    }
    close MAKEFILE;
    @sources = split(/ +/, $sources);
    @addsources = split(/ +/, $addsources);
    
    return (@sources, @addsources);
}
