#!/bin/perl

# debchange : update the debian changelog using your favorite visual editor
# Options:
# -n generate a new changelog bumping up the release number
#    otherwise add entry to existing changelog section.
# Christoph Lameter <clameter@debian.org>

$VISUAL=$ENV{"VISUAL"};

if (!$VISUAL) {
        $VISUAL=$ENV{"EDITOR"};
        if (!$VISUAL) {
		$VISUAL="joe"
	}
}

# Look for the debian changelog
until (-e "debian/changelog")
{
	chdir "..";
	if ($?)
	{
		printf "Cannot find a changelog to edit anywhere\n";
		exit(1);
	}
}

system("cp debian/changelog /tmp/ch");

if ($?) { die "Cannot copy changelog\n"; }


if ($ARGV[0] eq "-n" || -f "debian/RELEASED")
{
	if ($ARGV[0] eq "-n") {
		shift
	}
	if (-f "debian/RELEASED") {
		unlink("debian/RELEASED");
	}
	$TEXT="@ARGV";
	$DATE=`822-date`;chop $DATE;
	open(S,"</tmp/ch") || die "Cannot write /tmp/ch";
	$_=<S>;
	if (/^(.*) \((.*)-(.*)\) (.*); urgency=(.*)/) {
		($PACKAGE,$VERSION,$RELEASE,$DISTRIB,$URGENT) = ($1,$2,$3,$4,$5);
		$separator="-";
	} elsif  (/^(.*) \((.*)\.(.*)\) (.*); urgency=(.*)/) {
		($PACKAGE,$VERSION,$RELEASE,$DISTRIB,$URGENT) = ($1,$2,$3,$4,$5);
		$separator=".";
	} else {
		die "Header of changelog has bad format\n";
	}
	while (<S>) {
		if (/^ -- (.* .*) <(.*)>  .* [+-][0-9][0-9][0-9][0-9]/) {
			($MAINTAINER,$EMAIL) = ($1,$2);
			last;
		}
	}
	if (!$MAINTAINER) {
		print 'Format error in debian/changelog incorrect "  --" line'."\n";
		exit(1);
	}
	close(S);
	open(O,">debian/changelog");
	$RELEASE++;
	printf O "$PACKAGE ($VERSION$separator$RELEASE) $DISTRIB; urgency=$URGENT\n\n";
	printf O "  * ";
	printf O $TEXT if ($TEXT);
	printf O "\n\n -- $MAINTAINER <$EMAIL>  $DATE\n\n";
	open S,"</tmp/ch";
} else {
	# This means we just have to generate a new * entry in changelog
	$TEXT="@ARGV";
	open(O,">debian/changelog") || die "Cannot open debian/changelog\n";
	open(S,"</tmp/ch") || die "Cannot open /tmp/ch\n";
	# The first two lines stay the same
	if ($_=<S>) { printf O; } else { die "No first line in changelog\n"; }
	if ($_=<S>) { printf O; } else { die "No second line in changelog\n"; }
	# And the third gets the new entry
	if ($TEXT) {
		printf O "  * $TEXT\n";
	} else {
		printf O "  * \n";
	}
}

# Copy the rest of the changelog file to new one
while (<S>) { printf O; }

close S;
close O;

unlink "/tmp/ch";

# Now Run the Editor
if (! $TEXT) {
	exec("$VISUAL +3 debian/changelog");
}
