#!/usr/bin/perl

use strict;
use warnings;

use DHT;

usage <<__END__;
dch - Append the changelog

Usage: dht dch [debchange option]

This is a wrapper for debchange(1), which will implement our custom heuristics
of whether a new changelog entry should be created, or the current one be
amended: If there current one is tagged, create a new one, else append the
current one.

It passes either --append or --increment to debchange, so you should not.
__END__

manpage <<__END__;

Usage: dht dch [debchange option]

This is a wrapper for debchange(1), which will implement our custom heuristics
of whether a new changelog entry should be created, or the current one be
amended: If there current one is tagged, create a new one, else append the
current one.

It passes either --append or --increment to debchange, so you should not.
__END__

my $changelog = "debian/changelog";
unless (-r $changelog) {
	print "ERROR: Could not find $changelog\n";
	next;
}
open CHANGELOG, '<', $changelog or die @!;
my $firstline = <CHANGELOG>;
if ($firstline =~ m/([\w-]+) \(([\w:~.+-]+)\) ([\w-]+);/) {
	my ($source, $version, $suite) = ($1, $2, $3);
	my $tag = sprintf "%s_v%s", $source, $version;
	$tag =~ tr/:~/_/;

	my $option;
	if (system(qw/git show-ref --quiet/, "refs/tags/$tag") == 0) {
		# There is a tag. use --increment
		$option = "--increment";
	} else {
		# There is no tag. use --append
		$option = "--append";
	}
	system("debchange",$option,@ARGV);
} else {
	printf STDERR "Cannot parse %s:\n%s", $changelog, $firstline;
	next
}
