#!/usr/bin/perl

use strict;

if ($#ARGV < 1) {
    print <<EOT;
	Usage: update_cfg.pl <file> [<section>:]<name> <value>
EOT
    exit 1;
}

my $filename = shift;
my $name = shift;
my $value = shift;


my $lines = '';
my @sections = ();
my $section = '';
my $found = 0;

open XML, "<$filename" or die "Can't open file '$filename': $!";
while (<XML>) {
    my $line = $_;
    if ($line =~ /<key\s+name="(.*)">/) {
	push @sections, $1;
	$section = join('.', @sections);
    } elsif ($line =~ /<\/key>/) {
	pop @sections;
	$section = join('.', @sections);
    } elsif ($line =~ /(^.*<t\w+\s+name=")(.*)(">)(.*)(<\/t\w+>.*$)/m) {
	my $id = ($section eq '') ? $2 : "${section}:$2";
	if ($id eq $name) {
	    $line = join('', $1, $2, $3, $value, $5, "\n");
	    $found++;
	}
    }
    $lines .= $line;
}
close XML;

open XML, ">${filename}" or die "Can't open file '${filename}': $!";
print XML $lines;
close XML;

my $exitcode = $found > 0 ? 0 : 1;

if ($exitcode) {
   print "value not found, configuration not changed\n";
} else {
   print "configuration changed\n";
}

exit $exitcode;
