#!/usr/bin/perl -w

use strict;

# This is the version in configure.ac:
my $official_version = $ARGV[0];
my $lastrelease = "unknown";

my $state = "unknown";
if (-e "_darcs/hashed_inventory") {
  my $patches = `darcs changes --from-tag '$official_version' --count 2>/dev/null`;
  unless ($patches) {
    # Looks like "darcs changes" does not support --count argument
    $patches = grep(/^\S/, `darcs changes --from-tag '$official_version'`);
  }
  $patches = $patches - 1 if ($patches > 0);
  if ($patches == 0) {
    if ($official_version =~ /pre(\d+)/) {
      $state = "prerelease $1";
    } elsif ($official_version =~ /rc(\d+)/) {
      $state = "release candidate $1";
    } elsif ($official_version =~ /^[0-9\.]+$/) {
      $state = "release";
    } else {
      $state = "tag";
    }
  } elsif ($patches > 1) {
    $state = "+ $patches patches";
  } else {
    $state = "+ $patches patch";
  }
  
  if (open(X,"darcs changes -t '^[0-9\.]+\$' --reverse |")) {
    while (<X>) {
      if (/tagged (\S+)$/) {
        $lastrelease = $1;
      }
    }
  }
} elsif (open(FIN,"release/STATE")) {
  my $statestring = <FIN>;
  if ($statestring =~ /\((.+)\)/) {
    $state = $1;
  }
  close(FIN);
}

print "$official_version ($state)\n";

if (open(FIN,"src/ThisVersion.lhs.in") && open(FOUT,">src/ThisVersion.lhs.tmp")) {
  while (<FIN>) {
    s/\@DARCS_VERSION_STATE\@/$state/g;
    s/\@DARCS_VERSION\@/$official_version/g;
    print FOUT $_;
  }
  close(FIN);
  close(FOUT);
}


my $replace = 1;
if (open(FIN,"src/ThisVersion.lhs") && open(FTMP,"src/ThisVersion.lhs.tmp")) {
  my ($old, $new);
  read FIN, $old, 10000;
  read FTMP, $new, 10000;
  $replace = $old ne $new;
  close(FIN);
  close(FTMP);
}

if ($replace) {
  rename "src/ThisVersion.lhs.tmp", "src/ThisVersion.lhs";
} else {
  unlink "src/ThisVersion.lhs.tmp";
}

if (open(FIN,"doc/index.html.in") && open(FOUT,">doc/index.html")) {
  while (<FIN>) {
    s/VERSION/$official_version/g;
    s/RELEASE/$lastrelease/g;
    print FOUT $_;
  }
  close(FIN);
  close(FOUT);
}
