In Konfiguration angegebene Anwendungen in PATH suchen
[kivitendo-erp.git] / SL / LxOfficeConf.pm
1 package SL::LxOfficeConf;
2
3 use strict;
4
5 use Config::Std;
6 use Encode;
7
8 my $environment_initialized;
9
10 sub read {
11   my ($class, $file_name) = @_;
12
13   read_config 'config/lx_office.conf.default' => %::lx_office_conf;
14   _decode_recursively(\%::lx_office_conf);
15
16   $file_name ||= 'config/lx_office.conf';
17
18   if (-f $file_name) {
19     read_config $file_name => my %local_conf;
20     _decode_recursively(\%local_conf);
21     _flat_merge(\%::lx_office_conf, \%local_conf);
22   }
23
24   _init_environment();
25   _determine_application_paths();
26 }
27
28 sub _decode_recursively {
29   my ($obj) = @_;
30
31   while (my ($key, $value) = each %{ $obj }) {
32     if (ref($value) eq 'HASH') {
33       _decode_recursively($value);
34     } else {
35       $obj->{$key} = decode('UTF-8', $value);
36     }
37   }
38 }
39
40 sub _flat_merge {
41   my ($dst, $src) = @_;
42
43   while (my ($key, $value) = each %{ $src }) {
44     if (!exists $dst->{$key}) {
45       $dst->{$key} = $value;
46
47     } else {
48       map { $dst->{$key}->{$_} = $value->{$_} } keys %{ $value };
49     }
50   }
51 }
52
53 sub _init_environment {
54   return if $environment_initialized;
55
56   my %key_map = ( lib  => { name => 'PERL5LIB', append_path => 1 },
57                   path => { name => 'PATH',     append_path => 1 },
58                 );
59   my $cfg     = $::lx_office_conf{environment} || {};
60
61   while (my ($key, $value) = each %{ $cfg }) {
62     next unless $value;
63
64     my $info = $key_map{$key} || {};
65     $key     = $info->{name}  || $key;
66
67     if ($info->{append_path}) {
68       $value = ':' . $value unless $value =~ m/^:/ || !$ENV{$key};
69       $value = $ENV{$key} . $value;
70     }
71
72     $ENV{$key} = $value;
73   }
74
75   $environment_initialized = 1;
76 }
77
78 sub _determine_application_paths {
79   my @paths = grep { $_ } split m/:/, $ENV{PATH};
80
81   foreach my $key (keys %{ $::lx_office_conf{applications} }) {
82     my ($program) = split m/\s+/, $::lx_office_conf{applications}->{$key};
83     next if $program =~ m|/|;
84
85     foreach my $path (@paths) {
86       next unless -f "${path}/${program}";
87       $::lx_office_conf{applications}->{$key} = "${path}/" . $::lx_office_conf{applications}->{$key};
88       last;
89     }
90   }
91 }
92
93 1;