#!/usr/bin/perl -w
# debhelper format -- lintian check script

# Copyright (C) 1999 by Joey Hess
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, you can find it on the World Wide
# Web at http://www.gnu.org/copyleft/gpl.html, or write to the Free
# Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
# MA 02111-1307, USA.

($#ARGV == 1) or fail("syntax: debhelper <pkg> <type>");
my $pkg = shift;
my $type = shift;

# Parse the debian/rules file, and try to figure out if debhelper commands are
# run in it that like to modify maintainer scripts. Those debhelper commands can
# be found by "grep -l autoscript /usr/bin/dh_*", but I'll hardcode them here.
my %commands;
map { $commands{$_}=1 } qw{dh_installdocs dh_installemacsen dh_installinfo
                           dh_installinit dh_installmenu dh_installmime
			   dh_installmodules dh_installwm dh_installxaw
			   dh_suidregister dh_installxfonts
                        };

open(RULES, "debfiles/rules") or fail("cannot read debian/rules: $!");
my $seencommand='';
while (<RULES>) {
	if (/^\s+(dh_.*)/ && $commands{$1}) {
		$seencommand=1;
		last;
	}
}
close RULES;

exit unless $seencommand;

# If we got this far, they need to have #DEBHELPER# in their scripts.
# search for scripts that look like maintainer scripts.
opendir(DEBIAN, 'debfiles') 
	or fail("Can't open debfiles directory.");
while (defined(my $file=readdir(DEBIAN))) {
	next unless $file=~m/^(?:.*\.)?(?:post|pre)(?:inst|rm)$/;

	open(IN,"debfiles/$file")
		or fail("Can't open debfiles/$file: $!");
	my $seentag='';
	while (<IN>) {
		if (/#DEBHELPER#/) {
			$seentag=1;
			last;
		}
	}
	close IN;
	
	if (! $seentag) {
		print "W: $pkg: maintainer-script-lacks-debhelper-token debian/$file\n";
	}
}
closedir(DEBIAN);

# -----------------------------------

sub fail {
  if ($_[0]) {
    print STDERR "internal error: $_[0]\n";
  } elsif ($!) {
    print STDERR "internal error: $!\n";
  } else {
    print STDERR "internal error.\n";
  }
  exit 1;
}
