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

our $author     = 'Thaddeus H. Black';
our $email      = 't@b-tk.org';

# This helper script automatically updates debram's issue date in
# several files (the files are named in the following block).  The
# script accepts date and time in any format the date(1) command
# understands, but it writes the date (and time) to each file in that
# file's appropriate format.  Example usage:
#
#   $ update-date '24 Jan 2005 21:00'
#
# When also running the helper/update-ver script, you probably want to
# run that script first, then this one.  Otherwise debian/changelog is
# updated in a different manner than you probably thought to update it.
#
# (Bug:  This script, like helper/update-ver, uses far too much memory
# when it runs.  Because the script is only a development helper,
# because few people will ever run the script, because the memory waste
# is theoretically inaesthetic but practically probably inconsequential,
# there is no plan to fix the bug.)
#
#

our $debram_txt = "${FindBin::RealBin}/../debram.txt";
our $debram_1   = "${FindBin::RealBin}/../debram.1";
our $descloc    = "${FindBin::RealBin}/DescLoc";
our $changelog  = "${FindBin::RealBin}/../debian/changelog";

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

my $ind;
@ARGV == 1 && ( $ind = `date -d'$ARGV[0]'`, !$? )
  or die "usage: $0 date\n";
my $dtd = `date -d'$ind' +'%e %B %Y'`; $dtd =~ s/^\s*//;
my $cld = `date -d'$ind' -R`;
chomp $dtd;
chomp $cld;

open DT, '<', $debram_txt;
open D1, '<', $debram_1;
open DL, '<', $descloc;
open CL, '<', $changelog;
my @dt = <DT>;
my @d1 = <D1>;
my @dl = <DL>;
my @cl = <CL>;
close DT;
close D1;
close DL;
close CL;

$dt[8] =~ s/^(Version )(\d+\.\d+\.\d+)(, )(\S(?:.*?\S)??)\s*$/$1$2$3$dtd\n/
  or warn "$warn_msg$debram_txt\n";
$d1[1] =~ s/^(  ")([^"]*?)(")/$1$dtd$3/
  or warn "$warn_msg$debram_1\n";
{
  my $i = 0;
  ++$i until $i > $#dl || $dl[$i] =~ /^DATA\s*$/;
  ++$i until $i > $#dl || $dl[$i] =~ /^The issue date is\s*$/;
  $i += 2;
  $i <= $#dl && $dl[$i] =~ s/^(  )(\S(?:.*?\S)??)\s*$/$1$dtd\n/
    or warn "$warn_msg$descloc\n";
}
{
  my $i = 0;
  ++$i until $i > $#cl ||
    $cl[$i] =~ s/^( -- $author <$email>  )(\S(?:.*?\S)??)\s*$/$1$cld\n/;
  $i <= $#cl or warn "$warn_msg$changelog\n";
}

open DT, '>', $debram_txt;
open D1, '>', $debram_1;
open DL, '>', $descloc;
open CL, '>', $changelog;
print DT @dt;
print D1 @d1;
print DL @dl;
print CL @cl;
close DT;
close D1;
close DL;
close CL;

