#!/usr/bin/perl

use strict;
use warnings;

use lib '../lib';

my $fil = "version.h";
my $ver;

foreach (@ARGV) {
  my ($opt, $arg) = (split(/=/, $_, 2));
  if ($opt eq '--with-version') {
    if ($arg =~ /^(\d)\.(\d\d\d)_?(\d\d\d)/) {
      $ver = join(".", $1*1, $2*1, $3*1);
    }
    else {
      $ver = $arg;
    }
  }
}

print "version.h.pl: creating $fil\n";
unless ($ver) {
  if (-e '../lib/Mail/SpamAssassin.pm') {
    eval {
      require Mail::SpamAssassin;
      $ver = Mail::SpamAssassin::Version();
    };
  }
  else {
    $@ = "File not found.";
  }
  unless ($ver) {
    die join("\n", "Failed to get the version from Mail::SpamAssassin.",
                   "Please use the --with-version= switch to specify it manually.",
                   "",
                   "The error was:",
                   $@,
          );
  }
}

open IN,  "<$fil.in" || die "Failed to open $fil.in: $!";
open OUT, ">$fil"    || die "Failed to open $fil: $!";

print OUT "/* $fil.  Generated by $0.  */\n";
foreach (<IN>) {
  s/(#define\s+VERSION_STRING\s+)".*"/$1"$ver"/;
  print OUT;
}

close IN;
close OUT;

