LiCoM::Config: Read the file `licom.conf' in the script's directory too, if it exists.
[licom.git] / lib / LiCoM / Config.pm
index 1c561a2..be8359f 100644 (file)
@@ -2,19 +2,99 @@ package LiCoM::Config;
 
 use strict;
 use warnings;
+use Carp (qw(cluck confess));
+
+use File::Basename (qw(dirname));
 
 use Exporter;
 
-@LiCoM::Config::EXPORT_OK = ('get_config');
+@LiCoM::Config::EXPORT_OK = (qw(get_config set_config read_config));
 @LiCoM::Config::ISA = ('Exporter');
 
+our $Config = {};
+
 return (1);
 
+=head1 EXPORTED FUNCTIONS
+
+=over 4
+
+=item B<get_config> (I<$key>)
+
+Returns the value for I<$key> or undef if it's unknown.
+
+=cut
+
 sub get_config
 {
-       my $file = @_ ? shift : '/etc/licom/licom.conf';
+       my $key = shift;
+
+       cluck ("\$key was not defined") unless (defined ($key));
+
+       if (!%$Config)
+       {
+               read_config ();
+       }
+
+       return ($Config->{$key});
+}
+
+=item B<set_config> (I<$key>, I<$value>)
+
+Sets the value of I<$key> to I<$value>.
+
+=cut
+
+sub set_config
+{
+       my $key = shift;
+       my $val = shift;
+
+       cluck ("\$key was not defined") unless (defined ($key));
+
+       $Config->{$key} = $val;
+}
+
+=item B<read_config> ([I<@files>])
+
+Read the config from the files given or F</etc/licom/licom.conf> and
+F<~/.licomrc> if no files were given.
+
+=cut
+
+sub read_config
+{
+       my @files = ('/etc/licom/licom.conf');
+
+       if (@_)
+       {
+               @files = @_;
+       }
+       elsif (defined ($ENV{'HOME'}) and (-d $ENV{'HOME'}))
+       {
+               push (@files, $ENV{'HOME'} . '/.licomrc');
+       }
+       elsif (defined ($ENV{'SCRIPT_FILENAME'}))
+       {
+               push (@files, dirname ($ENV{'SCRIPT_FILENAME'}) . '/licom.conf');
+       }
+
+       for (@files)
+       {
+               my $file = $_;
+               next unless (-r $file);
+
+               read_file ($file, $Config);
+       }
+
+       return ($Config);
+}
+
+sub read_file
+{
+       my $file   = @_ ? shift : '/etc/licom/licom.conf';
+       my $config = @_ ? shift : {};
        my $fh;
-       my $config = {};
 
        open ($fh, "< $file") or die ("open ($file): $!");
        for (<$fh>)
@@ -35,3 +115,11 @@ sub get_config
 
        return ($config);
 }
+
+=back
+
+=head1 AUTHOR
+
+Florian octo Forster E<lt>octo at verplant.orgE<gt>
+
+=cut