about summary refs log tree commit diff stats
path: root/leo.pl
blob: a82ef0710190eb85baae1474b0ab100a8eb470e5 (plain) (blame)
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#!/usr/bin/perl

use strict;
use warnings;

use IPC::Run3;
use Path::Tiny;
use Config::Tiny;
use POSIX qw(strftime);
use Getopt::Long qw/ GetOptions /;

my $version = "leo v0.4.3";

# Options.
my %options = (
    L_SIGN => $ENV{L_SIGN},
    L_GZIP => $ENV{L_GZIP},
    L_ENCRYPT => $ENV{L_ENCRYPT},
    L_SIGNIFY => $ENV{L_SIGNIFY},
);

GetOptions(
    \%options,
    qw{ verbose help version }
) or die "leo: error in command line arguments\n";

# Print version.
print $version, "\n" and exit 0 if $options{version};

# Configuration.

my $config_file = $ENV{XDG_CONFIG_HOME} || "$ENV{HOME}/.config";
$config_file .= "/leo.conf";

my $config = Config::Tiny->new;
$config = Config::Tiny->read( $config_file )
    or die "Cannot read config file: `$config_file'\n";

# Reading config file.

foreach my $key (sort keys $config->{_}->%*) {
    $options{$key} = $config->{_}->{$key};
}

# Die if user is using older config format.
die "leo: old config format detected\n"
    if exists $options{encrypt} or exists $options{sign};

my %profile;

foreach my $prof (sort keys $config->%*) {
    next if $prof eq "_";

    # Set global values to local profiles.
    foreach (qw(L_ENCRYPT L_SIGN L_SIGNIFY L_GZIP)) {
        $profile{$prof}{$_} = $options{$_};
    }

    foreach my $key (sort keys $config->{$prof}->%*) {
        # $profile{$prof} contains config values ($), {exclude}
        # (@), {backup} (@).

        # Set config values.
        if ( length($key) >= 2
             and substr($key, 0, 2) eq "L_") {
            $profile{$prof}{$key} = $config->{$prof}->{$key};
            next;
        }

        push @{ $profile{$prof}{exclude} }, $key and next
            if $config->{$prof}->{$key} eq "exclude";

        push @{ $profile{$prof}{backup} }, $key;
    }
}

my $date = date();
my $backup_dir = $options{backup_dir} || "/tmp/backups";

my @gpg_recipients;
@gpg_recipients = split / /, $options{gpg_recipients}
    if $options{gpg_recipients};

my $gpg_bin = $options{gpg_bin} || "gpg";
warn "[WARN] \$gpg_bin is set to `$gpg_bin'"
    unless $gpg_bin =~ /^[gpg|gpg2]$/;

# Print help.
HelpMessage() and exit 0 if scalar @ARGV == 0 or $options{help};

# Parsing the arguments.
foreach my $prof ( @ARGV ) {
    if ( $profile{ $prof } ) {
        print "--------  $prof";
        print " [Encrypt]" if $profile{$prof}{L_ENCRYPT};
        print " [Sign]"    if $profile{$prof}{L_SIGN};
        print " [Signify]" if $profile{$prof}{L_SIGNIFY};
        print " [gzip]"    if $profile{$prof}{L_GZIP};
        print "\n";

        my $file = "$backup_dir/${prof}/${date}.tar";
        $file .= ".gz" if $profile{$prof}{L_GZIP};

        path("$backup_dir/${prof}")->mkpath; # Create backup directory.
        backup($prof, $file);

        my $is_gpg_req = 1 if $profile{$prof}{L_SIGN} or $profile{$prof}{L_ENCRYPT};
        encrypt_sign($prof, $file) if $is_gpg_req;

        # gpg would've removed the `.tar' file.
        $file = "${file}.gpg" if $is_gpg_req;
        signify($prof, $file) if $profile{$prof}{L_SIGNIFY};
    } else {
        warn "[WARN] leo: no such profile :: `$prof' \n";
    }
}

sub backup {
    my $prof = shift @_;
    my $tar_file = shift @_;

    my @options = ("-C", "/");
    push @options, "-z" if $profile{$prof}{L_GZIP};

    my @backup_paths;
    foreach my $path ($profile{$prof}{backup}->@*) {
        # If it's a directory then walk it upto 1 level.
        if (-d $path) {
            my $iter = path($path)->iterator();
            while ( my $iter_path = $iter->() ) {
                push @backup_paths, path( $iter_path );
            }
        } else {
            push @backup_paths, path( $path );
        }
    }

    # Remove files that are to be excluded.
    foreach my $exclude ($profile{$prof}{exclude}->@*) {
        @backup_paths = grep !/$exclude/, @backup_paths;
    }

    # All paths should be relative to '/'.
    @backup_paths = map { $_->relative('/') } @backup_paths;

    tar_create($tar_file, @options, @backup_paths);
    $? # tar returns 1 on errors.
        ? die "Backup creation failed :: $?\n"
        : print "Backup: $tar_file\n";

    path($tar_file)->chmod(0600);
    print "File was compressed with gzip(1).\n"
        if $profile{$prof}{L_GZIP} and $options{verbose};

    tar_list($tar_file) if $options{verbose};
}

# Encrypt, Sign backups.
sub encrypt_sign {
    my $prof = shift @_;
    my $file = shift @_;

    my @options = ();
    push @options, "--default-key", $options{gpg_fingerprint}
        if $options{gpg_fingerprint};

    if ( $profile{$prof}{L_ENCRYPT} ) {
        push @options, "--encrypt";
        push @options, "--recipient", $options{gpg_fingerprint}
            if $options{gpg_fingerprint};
        push @options, "--recipient", $_
            foreach @gpg_recipients;
    }

    push @options, "--sign" if $profile{$prof}{L_SIGN};
    push @options, "--verbose" if $options{verbose};

    run3 [$gpg_bin, "--yes", "-o", "${file}.gpg", @options, $file];

    $? # We assume non-zero is an error.
        ? die "GPG failed :: $?\n"
        : print "GPG: $file.gpg\n";

    unlink $file or warn "[WARN] Could not delete `$file': $!\n";

    path("$file.gpg")->chmod(0600);
}

sub signify {
    my $prof = shift @_;
    my $file = shift @_;

    my @options = ( "-S",
                    "-s", $options{signify_seckey},
                    "-m", $file,
                    "-x", "${file}.sig",
                );

    run3 ["signify", @options];
    $? # Non-zero exit code is an error.
        ? die "Signify failed :: $?\n"
        : print "Signify: ${file}.sig\n";
}

sub HelpMessage {
    print qq{Backup files to $backup_dir.

Profile:\n};
    foreach my $prof (sort keys %profile) {
        print "    $prof";
        if ($options{verbose}) {
            print " [Encrypt]" if $profile{$prof}{L_ENCRYPT};
            print " [Sign]" if $profile{$prof}{L_SIGN};
            print " [Signify]" if $profile{$prof}{L_SIGNIFY};
            print " [gzip]" if $profile{$prof}{L_GZIP};
            print "\n";

            print "        + $_\n" foreach $profile{$prof}{backup}->@*;
            print "        - $_\n" foreach $profile{$prof}{exclude}->@*;
        }
        print "\n";
    }
    print qq{Options:
    --version [$version]
    --verbose
    --help
};
}

sub tar_create { run3 ["/bin/tar", "cf", @_]; }
sub tar_list { print "\n"; run3 ["/bin/tar", "tvf", @_]; print "\n";}

sub date { return strftime '%FT%T%z', gmtime() }