LiCoM::Config: Read the file `licom.conf' in the script's directory too, if it exists.
[licom.git] / lib / LiCoM / Config.pm
1 package LiCoM::Config;
2
3 use strict;
4 use warnings;
5 use Carp (qw(cluck confess));
6
7 use File::Basename (qw(dirname));
8
9 use Exporter;
10
11 @LiCoM::Config::EXPORT_OK = (qw(get_config set_config read_config));
12 @LiCoM::Config::ISA = ('Exporter');
13
14 our $Config = {};
15
16 return (1);
17
18 =head1 EXPORTED FUNCTIONS
19
20 =over 4
21
22 =item B<get_config> (I<$key>)
23
24 Returns the value for I<$key> or undef if it's unknown.
25
26 =cut
27
28 sub get_config
29 {
30         my $key = shift;
31
32         cluck ("\$key was not defined") unless (defined ($key));
33
34         if (!%$Config)
35         {
36                 read_config ();
37         }
38
39         return ($Config->{$key});
40 }
41
42 =item B<set_config> (I<$key>, I<$value>)
43
44 Sets the value of I<$key> to I<$value>.
45
46 =cut
47
48 sub set_config
49 {
50         my $key = shift;
51         my $val = shift;
52
53         cluck ("\$key was not defined") unless (defined ($key));
54
55         $Config->{$key} = $val;
56 }
57
58 =item B<read_config> ([I<@files>])
59
60 Read the config from the files given or F</etc/licom/licom.conf> and
61 F<~/.licomrc> if no files were given.
62
63 =cut
64
65 sub read_config
66 {
67         my @files = ('/etc/licom/licom.conf');
68
69         if (@_)
70         {
71                 @files = @_;
72         }
73         elsif (defined ($ENV{'HOME'}) and (-d $ENV{'HOME'}))
74         {
75                 push (@files, $ENV{'HOME'} . '/.licomrc');
76         }
77         elsif (defined ($ENV{'SCRIPT_FILENAME'}))
78         {
79                 push (@files, dirname ($ENV{'SCRIPT_FILENAME'}) . '/licom.conf');
80         }
81
82         for (@files)
83         {
84                 my $file = $_;
85                 next unless (-r $file);
86
87                 read_file ($file, $Config);
88         }
89
90         return ($Config);
91 }
92
93 sub read_file
94 {
95         my $file   = @_ ? shift : '/etc/licom/licom.conf';
96         my $config = @_ ? shift : {};
97         my $fh;
98
99         open ($fh, "< $file") or die ("open ($file): $!");
100         for (<$fh>)
101         {
102                 chomp;
103                 my $line = $_;
104
105                 if ($line =~ m/^(\w+):\s*"(.+)"\s*$/)
106                 {
107                         my $key = lc ($1);
108                         my $val = $2;
109
110                         $config->{$key} = $val;
111                 }
112         }
113
114         close ($fh);
115
116         return ($config);
117 }
118
119 =back
120
121 =head1 AUTHOR
122
123 Florian octo Forster E<lt>octo at verplant.orgE<gt>
124
125 =cut