#! /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, 0, "$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";

#
# Create a symlink for the category file
#
#symlink("$gnatssite","$gnatsdir/$site") || addconfig_die;

#
# Fix things from previous version
#
if (-d "$gnatsdir/gnats-db") {
	print "- The previous version put the gnats database under $gnatsdir\n";
	if (rename("$gnatsdir/gnats-db","$gnatsdbdir")) {
		print "  It has now been moved to $gnatsdbdir";
	} else {
		print "  You must move it to $gnatsdbdir";
	}
}
