#!/usr/bin/perl -w
use strict;
use Getopt::Long;

my $section;
my $file;

sub set {
    my $setting = shift;
    my $oldvalue = shift;
    my $newvalue = shift;
    
    if (defined($newvalue))
    {
	print OUT "$setting=$newvalue\n"
	     or die "Cannot write to $file.new: $!";
    }
}

sub doit {
    my $setting;
    my $value;
    ($setting,$value) = split("=",shift);

    die "No filename given\n" if (!defined($file));
    die "No section given\n" if (!defined($section));

    open(IN,"<$file") or die "Cannot open $file for reading: $!\n";
    open(OUT,">$file.new") or die "Cannot open $file.new for writing: $!\n";

    my $insection = "none";
    my $done = 0;
    while (<IN>)
    {
	my $output = 1;
	if (/^\s*\[([^\]]+)\]\s*$/)
	{
	    if (!$done and $section eq $insection)
	    {
	    	set($setting,undef,$value);
	    	$done = 1;
	    }
	    $insection = $1;
	}
	elsif (/^\s*([\w\.]+)\s*=\s*\{\s*$/)
	{
		$insection = $insection . "::" . $1;
	    	if ($section eq $insection and $setting eq "")
		{
	    		print(OUT "$value = {\n")
				or die "Cannot write to $file.new: $!";
			$done = 1;
			$output = 0;
		}
	}
	elsif (/^\s*\}\s*$/)
	{
		$insection =~ s/::[^:]+//;
	}
	elsif (/^\s*([\w\.]+)\s*=\s*(.*)\s*$/)
	{
	#print "$insection $1=$2\n";
	    if ($section eq $insection and
	    	$setting ne "" and
	    	$setting eq $1)
	    {
		set($setting,$2,$value);
		$output = 0;
		$done = 1;
	    }
	}
	if ($output)
	{
	    print(OUT $_) or die "Cannot write to $file.new: $!";
	}
    }
	    
    if (!$done)
    {
	if ($section ne $insection)
	{
		die "Section $section doesn't exist\n";
	}
    	set($setting,undef,$value);
    	$done = 1;
    }

    close(OUT) or die "Cannot close $file.new: $!";
    close(IN) or die "Cannot close $file: $!";
    rename("$file.new",$file) or die "Cannot remame $file.new to $file";
}

GetOptions("file=s",\$file,"section=s",\$section,"<>",\&doit)
	|| die "Cannot parse command line\n";
