documentation snippet
[bak-git.git] / server.pl
1 #!/usr/bin/perl
2
3 =head1 bak-git
4
5 Simpliest possible backup from remote host (with natcat as
6 only depenency) to ad-hoc remote server
7
8 Install on client with:
9
10   echo install | nc 10.60.0.92 9001 > bak ; chmod 755 bak
11
12 =cut
13
14 use warnings;
15 use strict;
16 use autodie;
17 use IO::Socket::INET;
18 use File::Path;
19
20 my $dir = shift @ARGV || die "usage: $0 /backup/directory\n";
21
22 chdir $dir;
23 system 'git init' unless -e '.git';
24
25 my $server = IO::Socket::INET->new(
26         Proto     => 'tcp',
27         LocalPort => 9001,
28         Listen    => SOMAXCONN,
29         Reuse     => 1
30 ) || die $!;
31
32 while (my $client = $server->accept()) {
33         my ($command,$path,$message) = split(/\s+/,<$client>,3);
34         my $ip = $client->peerhost;
35
36         $message ||= '';
37
38         if ( $command eq 'install' ) {
39                 print $client '#!/bin/sh',$/,'echo $* | nc 10.60.0.92 9001',$/;
40                 next;
41         }
42
43         warn "$ip [$command] $path | $message\n";
44
45         if ( ! -d $ip ) {
46                 system 'ssh-copy-id', "root\@$ip";
47         }
48
49
50         my $dir = $path;
51         $dir =~ s{/[^/]+$}{};
52
53         mkpath "$ip/$dir" unless -e "$ip/$dir";
54
55         if ( $command eq 'add' ) {
56                 warn 'rsync', "root\@$ip:$path", "$ip/$path";
57                 system 'rsync', "root\@$ip:$path", "$ip/$path";
58                 system 'git', 'add', "$ip/$path";
59         } else {
60                 system 'rsync', "root\@$ip:$path", "$ip/$path";
61                 $message ||= "$command $ip $path";
62                 system 'git', 'commit', '-m', $message, "$ip/$path";
63         }
64
65 }
66