# handle UPC configuration files
package UPC::Config;

sub new {
    my $self = {};
    my $class = shift;

    return bless $self, $class;
}

sub parsefile {
    my $self = shift;

    my $filename = shift;

    if ( open( my $FILE, "<", $filename )) {
        my @config = <$FILE>;
        return parsetext( \@config );
    } else {
        return;
    }
}

sub parsetext {
    my $self = shift;
    my $text = shift;

    my %config;
    my $section = 'Global';

    if ( ref $text ne 'ARRAY' ) {
        my @text = split( /[\r\n]+/, $text );
        $text = \@text;
    }

    while ( my $line = shift @{$text} ) {
        $line =~ s/[\r\n]+$//;
        next if $line =~ /^#$/;
        my ( $newsection ) = $line =~ m{^#(\w+.+)$};
        if ( $newsection ) {
            $section = $newsection;
        } else {
            my ( $key, $value ) = $line =~ m{^(.+?)=(.*);};
            if ( $config{$section}->{$key}) {
                die "$key already used";
            }
            $config{$section} ||= {};
            $config{$section}->{$key} = $value;
        }
    }

    $self->{config} = \%config;
    return $self->{config};
}

1;
