#! /usr/bin/perl


###############################################################################
#
# Add local info to 'gnats' configuration file
#
$site       = "my-site";						# provided by 'init'
$gnatsdir   = "/usr/lib/gnats";					# provided by 'init'
$gnatsdbdir = "/var/gnats-db";					# provided by 'init'
$gnatssite  = "$gnatsdbdir/$site";				# provided by 'init'
$configfile = "$gnatsdbdir/gnats-adm/config";	# provided by 'init'

sub addconfig_die {
	die "Cannot update 'gnats' config file: $!\n";
}

#
# Slurp the entire config file
#
$delim = $/; undef $/;
open(CONFIG,"<$configfile") || addconfig_die;
$config = <CONFIG>;
close(CONFIG);
$/ = $delim;
@config = split(/\n/,$config);
$changed = 0;

#
# Replace the "unknown-site" with a best guess
#
for ($index=0; $index <= $#config; $index++) {
	if ($config[$index] =~ m/unknown-site/) {
		$config[$index] =~ s/unknown-site/$site/;
		$changed = 1;
	}
}

#
# Write out the changed config file
#
$config = join("\n",@config);
$config.= "\n";
if ($changed == 1) {
	rename("$configfile","$configfile.dpkg-old") || addconfig_die;
	open(CONFIG,">$configfile") || addconfig_die;
	print CONFIG $config;
	close(CONFIG);
	chmod 0644, "$configfile";
	chown $gnatsid,$gnatsgid, "$configfile";
	print "- Site name is $site  --  edit $configfile\n";
	print "  to change this and other defaults.\n";
}
print "- See Gnats 'info' on how to set up the categories, responsible, & submitters\n";
print "  files.  In Gnats-info, type 'g' for goto, followed by 'Local configuration'.\n";

system "chown -R gnats.gnats $gnatsdbpar";
system "find $gnatsdbpar -type d -print | xargs chmod g+s";
