#! /usr/bin/perl


###############################################################################
#
# Remove the 'gnats' tools from emacs
#
$emacsfile = "/etc/site-start.el";	# provided by 'init'

sub rmemacs_die {
	print "- Could not remove 'gnats' tools from emacs site-start: $!\n";
	return 0;
}

#
# Slurp the entire emacs site-start file
#
if (open(EMACS,"<$emacsfile") || rmemacs_die) {
	$delim = $/; undef $/;
	$emacs = <EMACS>;
	close(EMACS);
	$/ = $delim;
	@emacs = split(/\n/,$emacs);

#
# Remove any old entry for 'gnats'
#
	@newemacs = ();
	$found = 0;
	foreach $line (@emacs) {
		if ($line =~ m/----- Gnats-Load-Start -----/) {
			$found = 1;
		}
		if ($found == 0) {
			push(@newemacs,$line);
		}
		if ($line =~ m/-----  Gnats-Load-End  -----/) {
			$found = 0;
		}
	}

#
# Write out the changed site-start file
#
	$emacs = join("\n",@newemacs);
	$emacs.= "\n";
	if (rename("$emacsfile","$emacsfile.dpkg-old") || rmemacs_die) {
		if (open(EMACS,">$emacsfile") || rmemacs_die) {
			print EMACS $emacs;
			close(EMACS);
			chmod 0644, "$emacsfile";
		} else {
			rename("$emacsfile.dpkg-old","$emacsfile");
		}
	}
}
