Debian Codegraph @

lemonldap-ng-common/lib/Lemonldap/NG/Common/Conf/Backends/Overlay.pm

raw
1 package Lemonldap::NG::Common::Conf::Backends::Overlay;
2
3 use Lemonldap::NG::Common::Conf::Constants qw($hashParameters );
4 use JSON;
5
6 our $VERSION = '2.19.0';
7
8 sub load {
9 my ( $self, $cfgNum, $fields ) = @_;
10 my @files = eval { overList($self) };
11 if ($@) {
12 $Lemonldap::NG::Common::Conf::msg .= $@;
13 return undef;
14 }
15 my $conf =
16 &{"Lemonldap::NG::Common::Conf::Backends::$self->{overlayRealtype}::load"}
17 (@_);
18 my @errors;
19 foreach my $file (@files) {
20 if ( open my $f, '<', "$self->{overlayDirectory}/$file" ) {
21 local $/ = undef;
22 my $content = <$f>;
23 close $f;
24 if ( $file =~ $hashParameters ) {
25 eval { $content = JSON::from_json($content) };
26 if ($@) {
27 push @errors, "Bad over file $file: $@";
28 }
29 else {
30 $conf->{$file} = $content;
31 }
32 }
33 else {
34 $content =~ s/^\s*(.*?)\s*$/$1/;
35 $conf->{$file} = $content;
36 }
37 }
38 else {
39 push @errors, $!;
40 }
41 }
42 if (@errors) {
43 $Lemonldap::NG::Common::Conf::msg .= join "\n", @errors;
44 return undef;
45 }
46 return $conf;
47 }
48
49 sub store {
50 my ( $self, $fields ) = @_;
51 my @files = eval { overList($self) };
52
53 my @errors;
54 foreach my $file (@files) {
55 my $data = delete $fields->{$file};
56 if ( $self->{overlayWrite} ) {
57 if ( open my $f, '>', "$self->{overlayDirectory}/$file" ) {
58 print $f (
59 $file =~ $hashParameters ? JSON::to_json($data) : $data );
60 close $f;
61 }
62
63 else {
64 push @errors, "Unable to write over file $file: $@";
65 }
66 }
67 }
68
69 die join( "\n", @errors ) if $@;
70
71 return &{
72 "Lemonldap::NG::Common::Conf::Backends::$self->{overlayRealtype}::store"
73 }( $self, $fields );
74 }
75
76 sub overList {
77 my ($self) = @_;
78
79 my $overDir = $self->{overlayDirectory} or die 'Missing overlayDirectory';
80 die "$overDir directory doesn't exist" unless -d $overDir and -r $overDir;
81 opendir my $dir, $overDir or die $!;
82 my @files = grep /^[^\.]/, readdir $dir;
83 closedir $dir;
84 my @errors;
85
86 foreach my $file (@files) {
87 if ( open my $f, '<', "$overDir/$file" ) {
88 local $/ = undef;
89 my $content = <$f>;
90 close $f;
91 if ( $file =~ $hashParameters ) {
92 eval { $content = JSON::from_json($content) };
93 if ($@) {
94 push @errors, "Bad over file $file: $@";
95 }
96 else {
97 $conf->{$file} = $content;
98 }
99 }
100 else {
101 $content =~ s/^\s*(.*?)\s*$/$1/;
102 $conf->{$file} = $content;
103 }
104 }
105 }
106 die join "\n", @errors if @errors;
107 return @files;
108 }
109
110 sub AUTOLOAD {
111 my ($self) = @_;
112 die 'Missing overlayRealtype'
113 unless $self->{overlayRealtype};
114 eval
115 "require Lemonldap::NG::Common::Conf::Backends::$self->{overlayRealtype}";
116 die $@ if $@;
117 $AUTOLOAD =~ s/::Overlay::/::$self->{overlayRealtype}::/;
118 my @res = &{$AUTOLOAD}(@_);
119 return wantarray ? (@res) : $res;
120 }
121
122 1;