#! /usr/bin/perl


###############################################################################
#
# Add the 'gnats' system into the mail aliases
#
$site       = "my-site";		# provided by 'init'
$mailfile   = "/etc/aliases";	# provided by 'init'

sub addmail_die {
	die "Cannot add 'gnats' system into mail: $!\n";
}

#
# Slurp the entire aliases file
#
$delim = $/; undef $/;
open(MAIL,"<$mailfile") || addmail_die;
$mail = <MAIL>;
close(MAIL);
$/ = $delim;
@mail = split(/\n/,$mail);

#
# Re-activate any existing entries
#
$found = 0;
for ($index=0; $index <= $#mail; $index++) {
	if ($mail[$index] =~ m/gnats/) {
		$mail[$index] =~ s/#gnats#(.*gnats.*)$/$1/;
		$found = 1;
	}
}

#
# If not found, put the new aliases in
#
if ($found == 0) {
	push(@mail,"");
	push(@mail,"# begin gnats aliases");
	push(@mail,"gnats-admin:    gnats");
	print "- Gnats-admin mail is currently being sent to the 'gnats' userid\n";
	push(@mail,'bugs:           "| /usr/lib/gnats/queue-pr -q"');
	push(@mail,'query-pr:       "| /usr/lib/gnats/mail-query"');
	push(@mail,"$site-gnats:    bugs");
	print "- $site-gnats is your site alias\n";
	push(@mail,"# end gnats aliases");
}

#
# Write out the changed password file
#
$mail = join("\n",@mail);
$mail.= "\n";
rename("$mailfile","$mailfile.dpkg-old") || addmail_die;
open(MAIL,">$mailfile") || addmail_die;
print MAIL $mail;
close(MAIL);
chmod 0644, "$mailfile";
