#!/usr/bin/perl

$prog = &basename($0);
&help unless ($#ARGV == 2);

($config, $pattern, $replacement) = @ARGV;

@config = &readconfig($config);
$found=0;
for (-1 .. $#config) {
	$line_no = $_, $found=1, last if ($config[$_] =~ /$pattern/);
}
$line_no = ++$#config unless $found;

rename ($config, "$config.orig");
open(CONFIG, ">$config");
print CONFIG  @config[ -1 .. $line_no-1];
print CONFIG  "$replacement\n";
print CONFIG  @config[ $line_no+1 .. $#config];
close(CONFIG);
&shutdown;

sub basename {
        local ($name) = @_;
        local (@liste) = split("/", $name);

        return (pop(@liste));
}

sub shutdown {
	close CONFIG;
	exit 0;
}

sub error {
	print STDERR "$prog: @_\n";
	close CONFIG;
	exit 1;
}

sub readconfig {
	local (@ary);
	open(CONFIG, $config) || &error("can't open '$config'. $!.");
	@ary = <CONFIG>;
	close CONFIG;
	return(@ary);
}

sub help {
	print  <<EOF;

Usage: $prog config_file pattern replacement
EOF
	exit 1;
}
