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