#! /usr/bin/perl
use warnings;
use strict;
use integer;
use FindBin;
use lib $FindBin::RealBin;
use Def;

# 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.)
#
#

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

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

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

my $str_authe = "${Def::author} <${Def::email}>";
my $pat_authe;
{
  my $qm     = quotemeta $str_authe;
  $pat_authe = qr/$qm/;
}

$dt[8] =~
  s/^(Version )(\d+\.\d+\.\d+[a-z]?)(, )(\S(?:.*?\S)??)\s*$/$1$2$3$dtd\n/
  or warn "$warn_msg${Def::debram_txt}\n";
$d1[1] =~ s/^(  ")([^"]*?)(")/$1$dtd$3/
  or warn "$warn_msg${Def::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${Def::descloc}\n";
}
{
  my $i = 0;
  ++$i until $i > $#cl ||
    $cl[$i] =~ s/^( -- $pat_authe  )(\S(?:.*?\S)??)\s*$/$1$cld\n/;
  $i <= $#cl or warn "$warn_msg${Def::changelog}\n";
}
{
  my $i = $#rm;
  --$i until $i < 0 ||
    $rm[$i] =~ s/^.*\S.*\n/$str_authe, $cld\n/;
  $i >= 0 or warn "$warn_msg${Def::readme}\n"
}

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

