#!/usr/bin/perl
#
# Author: Petter Reinholdtsen <pere@hungry.com>
# Date:   2002-08-11
#
# Command line tool to modify .ini style files.

use strict;
use warnings;
use Config::IniFiles;

usage() if (4 > @ARGV);

my $filename = shift;
my $section  = shift;
my $key      = shift;
my $value    = shift;

# Make sure the file exist, as Config::IniFiles do not create empty
# config files.
if ( ! -f $filename ) {
    open(FILE, "> $filename") || die "Unable to create $filename";
    print FILE "[$section]\n";
    close(FILE);
} else {
    # Make sure the file contain more then just comment lines, because
    # the module fail to create an object if it does.
    open(FILE, "< $filename");
    my $count = 0;
    while (<FILE>) {
	chomp;
	s/[;\#].+$//;
	next if m/^\s*$/;
	$count++;
    }
    close(FILE);
    if (0 == $count) {
	open(FILE, ">> $filename") || die "Unable to append to $filename";
	print FILE "[$section]\n";
	close(FILE);
    }
}

my $ini = new Config::IniFiles( -file => $filename );

if ($ini) {
    $ini->AddSection($section);
    my $oldpath = $ini->newval($section, $key, $value);
    if ( ! $ini->RewriteConfig ) {
        print STDERR "error: Unable to set value for ".
            "section [$section], key='$key' in $filename!\n";
        exit 1;
    }
} else {
    print STDERR "error: Unable to load $filename!\n";
    exit 1;
}

exit 0;

sub usage {
    print "update-ini-file <file> <section> <variable> <value>\n";
    exit 0;
}
