#! /usr/bin/perl
use warnings;
use strict;
use integer;
use FindBin;

our $author     = 'Thaddeus H. Black';
our $email      = 't@b-tk.org';
our $default_changelog_items = <<END;
  * Updated the ramification data to reflect sarge as of this date.
  * Updated maint.txt.
END

# This helper script automatically updates debram's version number in
# several files (the files are named in the following block).  At the
# top of debian/changelog, it begins a new template entry.  Example
# usage:
#
#   $ update-ver 0.6.2
#
# See helper/update-date for further notes.
#
#

our $debram_txt = "${FindBin::RealBin}/../debram.txt";
our $def_h      = "${FindBin::RealBin}/../def.h";
our $descloc    = "${FindBin::RealBin}/DescLoc";
our $changelog  = "${FindBin::RealBin}/../debian/changelog";

our $pat_ver    = qr/(?<![.\d])\d+\.\d+\.\d+(?![\d])/;

my $warn_msg = "$0: cannot find version line in ";

my $ver;
@ARGV == 1
  or die "usage: $0 version\n";
$ver = $ARGV[0];
chomp $ver;
$ver =~ /^$pat_ver$/
  or die "usage: $0 version\n";

my $changelog_entry = <<END;
debram ($ver) unstable; urgency=low

$default_changelog_items
 -- $author <$email>  Thu,  1 Jan 1970 00:00:00 +0000

END

open DT, '<', $debram_txt;
open FH, '<', $def_h;
open DL, '<', $descloc;
open CL, '<', $changelog;
my @dt = <DT>;
my @fh = <FH>;
my @dl = <DL>;
my @cl = <CL>;
close DT;
close FH;
close DL;
close CL;

$dt[8] =~ s/^(Version )$pat_ver(,)/$1$ver$2/
  or warn "$warn_msg$debram_txt\n";
{
  my $i = 0;
  ++$i until $i > $#fh || $fh[$i] =~ s/^(#define VERSION\s+")$pat_ver(")/$1$ver$2/;
  $i <= $#fh or warn "$warn_msg$def_h\n";
}
{
  my $i = 0;
  ++$i until $i > $#dl || $dl[$i] =~ /^DATA\s*$/;
  ++$i until $i > $#dl || $dl[$i] =~ /^The version number is\s*$/;
  $i += 2;
  $i <= $#dl && $dl[$i] =~ s/^(  )(\S(?:.*?\S)??)\s*$/$1$ver\n/
    or warn "$warn_msg$descloc\n";
}
unshift @cl, $changelog_entry;

open DT, '>', $debram_txt;
open FH, '>', $def_h;
open DL, '>', $descloc;
open CL, '>', $changelog;
print DT @dt;
print FH @fh;
print DL @dl;
print CL @cl;
close DT;
close FH;
close DL;
close CL;

