#!/usr/bin/perl

use Getopt::Std;

################################################################################

getopts('v:t:o:p:');
$versionfile = $opt_v;

($versionfile ne "") || die("Version file missing");

################################################################################
#
# Find the topmost directory that belongs to this working copy.
#
sub getsvntop() {
  my $topdir = '.';

  sub getsvnroot($) {
    my $dir = shift;
    my @info = `svn info $dir 2>/dev/null`;
    @info = grep (/^Repository Root:/, @info);
    my $svnroot = $info[0];
    chomp($svnroot);
    return $svnroot;
  }

  my $svnroot = getsvnroot($topdir);
#  $svnroot || die("Not a svn directory");
  $svnroot || return;

  while(1) {
    my $trydir = "$topdir/..";
    my $tryroot = getsvnroot($trydir);
    last if ($svnroot ne $tryroot);
    $topdir = $trydir;
  }

  $topdir =~ s/^\.\///;

  return $topdir;
}

################################################################################

$epoch = time;
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($epoch);

open(VERFILE, "<", $versionfile) || die("Cannot open $versionfile");
$version = <VERFILE>;
close(VERFILE);
chomp($version);
($version, $revision, $patchlevel) = split(/\./, $version);

$topdir = getsvntop();
$svnversion = ($topdir && `cd $topdir; svnversion`) || "";

chomp($svnversion);
$svnversion =~ s/ *$//;
$svnversion =~ s/^ *//;
$svnversion =~ s/\r//;

################################################################################
#
# C header
#
if ($opt_o) {
    open(OUTPUT, ">", $opt_o) || die("Failed to open $opt_o");

    print OUTPUT "#include <tt/timestamp.h>\n\n";
    print OUTPUT "const struct timestamp app_timestamp = {\n";

    print OUTPUT "  .epoch      = $epoch,\n";
    print OUTPUT "\n";
    print OUTPUT "  .year       = " . ($year+1900) . ",\n";
    print OUTPUT "  .month      = " . ($mon+1) . ",\n";
    print OUTPUT "  .day        = $mday,\n";
    print OUTPUT "\n";
    print OUTPUT "  .hour       = $hour,\n";
    print OUTPUT "  .minute     = $min,\n";
    print OUTPUT "  .second     = $sec,\n";
    print OUTPUT "\n";
    print OUTPUT "  .version    = $version,\n";
    print OUTPUT "  .revision   = $revision,\n";
    print OUTPUT "  .patchlevel = $patchlevel,\n";
    print OUTPUT "  .svnversion = \"$svnversion\",\n";

    print OUTPUT "};\n\n";

    close OUTPUT;
}

################################################################################
#
# Plain string
#
if ($opt_p) {
    open(OUTPUT, ">", $opt_p) || die("Failed to open $opt_p");
    print OUTPUT "V$version.$revision.$patchlevel#$svnversion\n";
    close OUTPUT;
}

################################################################################
