#!/usr/bin/perl
# Copyright © 2009, David Bremner <bremner@unb.ca>
# This file may be distributed under the same terms as Perl: Artistic license or GPL 1+
use strict;
use Parse::DebControl;
use File::Slurp;

my $header="# Generated by refresh.pl from debian/packages.cfg. Edits may be lost.\n";
my %xform=(
	   'debian/copyright.in'=>{'#COPYRIGHT_STANZAS#'=>\&copyright_stanzas},
	   'debian/control.in'=> {'#MODULE_DESC_LIST#'=>\&module_desc_list},
	   'debian/watch.in'=> {'#WATCH_LIST#'=>\&watch_list}
);

my $parser=new Parse::DebControl;
my $pkgconf=$parser->parse_file("debian/packages.cfg",
				{useTieIxHash=>1,stripComments=>1}) || die "parser failed: $!";

for my $file (keys %xform) {

  my %subst=%{$xform{$file}};
  my $content=$header . read_file($file);
  for my $token (keys %subst){
    my $val=&{$subst{$token}};
    $content=~s/$token/$val/;
  }

  my $outfile= $file;
 
  $outfile =~ s/\.in$//;
  write_file($outfile,$content);
}

sub short_desc($){
  my $module=shift;
  my $desc=$module->{Description};
  $desc=~s/\n.*//;
  return $desc;
}
sub copyright_stanzas{
  my @list=map { $parser->write_mem($_); } @{$pkgconf};
  return join("\n\n",@list);
}

sub watch_list{
  my @list=map {$_->{Watch} . " ". $_->{'Upstream-Version'} } @{$pkgconf};
  return join("\n",@list);
}

sub module_desc_list{
  my @list=map {"  * ". $_->{Module} . " (". short_desc($_) .")" } @{$pkgconf};
  return join("\n",@list);
}


