summaryrefslogtreecommitdiffstats
path: root/lib/Tails/Persistence/Configuration/ConfigFile.pm
blob: 27237f7eb9f73bb0737fb4557672db6ded528a83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
=head1 NAME

Tails::Persistence::Configuration::ConfigFile - read, parse and write live-persistence.conf

=cut

package Tails::Persistence::Configuration::ConfigFile;
use 5.10.1;
use strictures 2;
use Moo;
use MooX::late;
use MooX::HandlesVia;

use autodie qw(:all);
use Carp;
use Function::Parameters;
use IPC::System::Simple qw{systemx};
use Tails::Persistence::Configuration::Line;
use Types::Path::Tiny qw{AbsPath};

use namespace::clean;


=head1 ATTRIBUTES

=cut

has 'config_file_path' => (
    isa      => AbsPath,
    is       => 'ro',
    coerce   => AbsPath->coercion,
    required => 1,
);

has 'lines' => (
    lazy_build    => 1,
    is            => 'rw',
    isa           => 'ArrayRef[Tails::Persistence::Configuration::Line]',
    handles_via   => [ 'Array' ],
    handles       => {
        all_lines => 'elements',
    },
);


=head1 CONSTRUCTORS

=cut

method BUILD (@args) {
    $self->config_file_path->exists || $self->config_file_path->touch;
}

method _build_lines () {
    return [
        grep { defined $_ } map {
            Tails::Persistence::Configuration::Line->new_from_string($_)
        } $self->config_file_path->lines({chomp => 1})
    ];
}


=head1 METHODS

=cut

=head2 output

Returns the in-memory configuration, as a string in the live-persistence.conf format.

=cut
method output () {
    my $out = "";
    foreach ($self->all_lines) {
        $out .= $_->stringify . "\n";
    }
    return $out;
}

=head2 save

Save the in-memory configuration to disk.
Throw exception on error.

=cut
method save () {
    my $config_file_was_empty = ! -s $self->config_file_path;
    unless ($config_file_was_empty) {
        $self->config_file_path->copy($self->config_file_path . '.bak');
    }
    $self->config_file_path->spew($self->output);
    $self->config_file_path->chmod(0600);
    # Ensure our changes land on the disk
    systemx('sync', $self->config_file_path->stringify);
    # Ensure changes made by other code (e.g. live-persist) are written
    # synchronously on the disk
    systemx('chattr', '+S', $self->config_file_path->stringify);
    # When persistence.conf was initially empty (for example, when
    # we're initializing a new persistent volume), let's backup the
    # (probably non-empty) version of it that we've just saved.
    if ($config_file_was_empty) {
        $self->config_file_path->copy($self->config_file_path . '.bak');
    }
}

no Moo;
1;