package Common::Config;

use strict;
use warnings;

use Exporter;

our @ISA = qw(Exporter);

## Parameters: ref to array, or @ARGV
## Returned value:
##          hash with params
sub readParams {
    my $array = shift;
    $array = \@ARGV
		unless $array;
    
	my %hash = ();
	foreach my $cfgline (@$array) {
        $hash{$1} = $2
			if( $cfgline =~ /^\s*([^ ]+)\s*=\s*(.*)$/ );
    }
    return \%hash;
}


## Description: reads config file, parse keys, values
##              if key, used in some value not found, tries to get it from ENV
sub readConfig {
    my $cfgfile = shift or die "config file should be given!";
    
	my %hash = ();

	my $line_num = 0;
	open(CFG, $cfgfile) or die "Can't open config file '$cfgfile'!";
    while( <CFG> ) {
		$line_num++;
		## remove msdos CR
        s/\r//;
        
		## skip comments
		next
			if (/^\s*\#/);
        
		my $err;
		if( /^\s*([^ ]+)\s*=\s*(.*)$/ ) {
            my $key = $1;
            my $val = $2;
            while( !$err && $val =~ /\$(.+)\$/ ) {
				## skip line with wrong $KEY$
				$hash{$1} = $ENV{$1}
					if( !defined($hash{$1}) && defined($ENV{$1}) );
				unless( defined $hash{$1} ) {
					warn "'$1' key is not found in config at line $line_num!\n";
					$err = 1;
					next;
				}
                
				my $_val = $hash{$1};
                ##$_val = $1
				##	unless ($_val);
                $val =~ s/\$.+\$/$_val/;
            }
            $hash{$key} = $val;
        }
    }
    close(CFG);
    
	return \%hash;
}


our @EXPORT = qw(
	readParams
	readConfig
);


1;
