package mUtil::Config;

# config file contains section [SECTION] 
# with key/value pairs sepatated by blank 

sub new {
	# parameter: 1) config file path
	my $my_data = {
		config_file      => $_[1],
		sections         => {} };

	bless $my_data;
	return $my_data;
}

sub loadSection {
	my $self = shift;
	my $name = shift;
	
	my $result = 0;
	
	if (exists($self->{'sections'}->{$name})) {
		$result = 1;
	}
	else {
		my $v = [];
		open (FILE, $self->{'config_file'}) || die "Could not open file: ".$self->{'config_file'};
		my $sectionRunning = 1;
		while (defined(my $line = <FILE>) && $sectionRunning) {
			chomp($line);
			if (length($line) > 0 && substr($line,0,1) ne '#') {
	
				# no comment line
	
				# search section start
				if ($line eq "[".$name."]") {
	
					# read section data
					$result = 1;
					while (defined($line = <FILE>) && $sectionRunning) {
						chomp($line);
						if (length($line) > 0 && substr($line,0,1) ne '#') {
							if (substr($line,0,1) eq '[') {
								$sectionRunning = 0;
							}
							else {
								push(@$v, $line);
							}
						}
					}
				}
			}
		}
		close(FILE);
		
		$self->{'sections'}->{$name} = $v if ($result);
		
	}
	return $result;
}

sub getConfig {
	my $self = shift;
	my $section = shift;
	my $key = shift;
	my $def_val = shift; # optional default value
	
	die ("Cannot load config section $section") unless $self->loadSection($section);
	my $sec_arr_ref = $self->{'sections'}->{$section};
	foreach my $line (@$sec_arr_ref) {
		my ($first,$second) = $line =~ /(.*?)\s+(.*)/;
		if ($first eq $key) {
			return $second;
		}
	}
	return $def_val;
}

sub requireConfig {
	my $self = shift;
	die ("No config entry for @_") unless defined (my $result = $self->getConfig(@_));
	return $result;
}

1;
