#!/usr/bin/perl -w
#
# Creates changelog for packages from Changelog files in the apps
#
# $Id$
#

use strict;
use Date::Manip;
use File::Basename;
use English;

sub changelog {

my $dtype = shift;
my $pkg = shift;
my $pbtag = shift;
my $dsuf = shift;
my $path = shift;
my $OUTPUT = shift;

my $log = "";

# For date handling
$ENV{LANG}="C";

return("\n") if ((not (defined $dtype)) || ($dtype eq "") || 
		(not (defined $pkg)) || ($pkg eq "") || 
		(not (defined $pbtag)) || ($pbtag eq "") || 
		(not (defined $dsuf)) || ($dsuf eq "") || 
		(not (defined $path)) || ($path eq "") || 
		(not (defined $OUTPUT)) || ($OUTPUT eq ""));

my $chglog = "$ENV{'PBROOT'}/$path/ChangeLog";
if (! -f $chglog) {
	print "Unable to find the ChangeLog file ($chglog) for $pkg\n";
	return("\n");
}

open(INPUT,"$chglog") || die "Unable to open $chglog (read)";

# Skip first 4 lines
my $tmp = <INPUT>;
$tmp = <INPUT>;
$tmp = <INPUT>;
if ($dtype eq "announce") {
	print $OUTPUT $tmp;
}
$tmp = <INPUT>;
if ($dtype eq "announce") {
	print $OUTPUT $tmp;
}

my $first=1;

# Handle each block separated by newline
while (<INPUT>) {
	my ($ver, $date) = split(/ /);
	my $ver2;
	$ver =~ s/^v//;
	chomp($date);
	$date =~ s/\(([0-9-]+)\)/$1/;
	#print "**$date**\n";
	my $ndate = UnixDate($date,"%a", "%b", "%d", "%Y");
	my $n2date = &UnixDate($date,"%a, %d %b %Y %H:%M:%S %z");
	#print "**$ndate**\n";
	if (($dtype eq "rpm") || ($dtype eq "fc")) {
		if ($ver !~ /-/) {
			if ($first eq 1) {
				$ver2 = "$ver-$pbtag$dsuf";
				$first=0;
			} else {
				$ver2 = "$ver-1$dsuf";
			}
		} else {
			$ver2 = "$ver$dsuf";
		}
		print $OUTPUT "* $ndate $confparam{'packager'} $ver2\n";
		print $OUTPUT "- Updated to $ver\n";
		}
	if ($dtype eq "deb") {
		print $OUTPUT "$pkg ($ver) unstable; urgency=low\n";
		print $OUTPUT "\n";
		}

	$tmp = <INPUT>;	
	while ($tmp !~ /^$/) {
		if ($dtype eq "deb") {
			print $OUTPUT "  * $tmp";
		} elsif ($dtype eq "rpm") {
			print $OUTPUT "$tmp";
		} else {
			print $OUTPUT "$tmp";
		}
		last if (eof(INPUT));
		$tmp = <INPUT>;
	}
	print $OUTPUT "\n";

	if ($dtype eq "deb") {
		print $OUTPUT " -- $confparam{'packager'} $n2date\n\n";
		print $OUTPUT "\n";
		}

	last if (eof(INPUT));
	last if ($dtype eq "announce");
}
close(INPUT);
return("\n");
}
1;
