#!/usr/bin/perl

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

require '/usr/lib/localization-config/common/log.pl';

# Helper subroutine to enable creation, initialization and 
# setting of configuration files with given values.
# This is to be used in post-installation scripts.
# It supports configuration files of the following form:
# [section]
# key1 = value1
# key2 = value2
# etc.
#
# This is the format used in KDE config files, amongst others.
# Do NOT use in configuration files in a different format, eg. XML.

sub postconfig {
    # The arguments needed are:
    # createfile:  boolean, if set to 'true' the file will also be created
    # filename:    this is the name of the configuration file
    # conf_values: the associative array used to hold all key/value pairs.
    
    my ($createfile, $filename, $conf_values) = @_;
    
    my @sections;
    for my $fullkey (sort keys %$conf_values) {
        my ($section) = $fullkey =~ m/(.*)\//;
        push(@sections, $section);
    }
    
    # Create file if not existent and $createfile is 'true'
    if ($createfile eq 'true') {
        if ( ! -f $filename ) {
            open(FILE, "> $filename") || log_die("$0: Unable to create $filename");
            foreach my $section (@sections) {
                print FILE "[".$section."]\n";
            }
            close(FILE);
        }
    }
    
    # Open configuration file. If it does not exist and 
    # has not been created previously, ie $createfile is set
    # to 'false' then postconfig() will fail.
    my $ini = new Config::IniFiles( -file => $filename)
        or log_die("$0: Can't open $filename: $!");

    # For each key/value pair, make the corresponding changes in the
    # configuration file.
    for my $fullkey (sort keys %$conf_values) {
        my ($section, $key) = $fullkey =~ m/(.*)\/(.*)/;
        $ini->newval($section, $key, $conf_values->{$fullkey});
    }

    # Write the changes back to the file. The script must run with
    # appropriate access rights for this to succeed.
    $ini->RewriteConfig or log_die("$0: Can't save $filename: $!");

    return;
}

1;
