make destination directory if needed
[bak-git.git] / bak-git-server.pl
1 #!/usr/bin/perl
2
3 =head1 bak-git
4
5 Simple tracking of remote files in central git repository
6 with only shell, netcat, rsync and ssh on client
7
8 Start server, install on remote-host or upgrade with:
9
10   ./bak-git-server.pl /path/to/backup 192.168.42.42
11         [--install remote-host]
12         [--upgrade]
13
14 You will want to add following to C<~/.ssh/config>
15
16   RemoteForward 9001 localhost:9001
17
18 bak command overview:
19
20   bak add /path
21   bak commit [/path [message]]
22   bak diff [host:][/path]
23   bak status [/path]
24   bak log [/path]
25
26   bak ch[anges]
27   bak revert [host:]/path
28
29   bak cat [host:]/path
30
31   bak - push all changed files to server
32
33 See L<http://blog.rot13.org/bak-git> for more information
34
35 =cut
36
37 use warnings;
38 use strict;
39 use autodie;
40 use IO::Socket::INET;
41 use File::Path;
42 use Getopt::Long;
43
44 my $upgrade = 0;
45 my $install;
46
47 GetOptions(
48         'upgrade!'  => \$upgrade,
49         'install=s' => \$install,
50 ) || die "$!\n";
51
52 my ( $dir, $server_ip ) = @ARGV;
53 die "usage: $0 /backup/directory 127.0.0.1\n" unless $dir;
54 $server_ip ||= '127.0.0.1';
55
56 my $shell_client = <<__SHELL_CLIENT__;
57 #!/bin/sh
58 echo \$USER/\$SUDO_USER `hostname` `pwd` \$* | nc $server_ip 9001
59 __SHELL_CLIENT__
60
61 chdir $dir;
62 system 'git init' unless -e '.git';
63
64 if ( $upgrade || $install ) {
65         open(my $fh, '>', '/tmp/bak');
66         print $fh $shell_client;
67         close($fh);
68         chmod 0755, '/tmp/bak';
69
70         my @hosts = grep { -d $_ } glob '*';
71         @hosts = ( $install ) if $install;
72
73         foreach my $hostname ( @hosts ) {
74                 warn "install on $hostname\n";
75                 system 'ssh-copy-id', "root\@$hostname" if ! -d $hostname;
76                 system "scp /tmp/bak root\@$hostname:/usr/local/bin/";
77                 system "ssh root\@$hostname apt-get install -y rsync";
78         }
79 }
80
81 my $server = IO::Socket::INET->new(
82         Proto     => 'tcp',
83         LocalAddr => $server_ip,
84         LocalPort => 9001,
85         Listen    => SOMAXCONN,
86         Reuse     => 1
87 ) || die $!;
88
89
90 warn "dir: $dir listen: $server_ip:9001\n"
91         , $shell_client
92 ;
93
94 sub rsync {
95         warn "# rsync ",join(' ', @_), "\n";
96         system 'rsync', @_;
97 }
98
99 sub pull_changes {
100         my $hostname = shift;
101         system "find $hostname -type f | sed 's,$hostname,,' > /tmp/$hostname.list";
102         if ( @_ ) {
103                 open(my $files, '>>', "/tmp/$hostname.list");
104                 print $files "$_\n" foreach @_;
105                 close($files);
106         }
107         rsync( qw( -avv --files-from /tmp/$hostname.list root\@$hostname:/ $hostname/ ) );
108 }
109
110 while (my $client = $server->accept()) {
111         my $line = <$client>;
112         chomp($line);
113         warn "<<< $line\n";
114         my ($user,$hostname,$pwd,$command,$rel_path,$message) = split(/\s+/,$line,6);
115         $hostname =~ s/\..+$//;
116
117         my $on_host = '';
118         if ( $rel_path =~ s/^([^:]+):(.+)$/$2/ ) {
119                 if ( -e $1 ) {
120                         $on_host = $1;
121                 } else {
122                         print $client "host $1 doesn't exist in backup\n";
123                         next;
124                 }
125         }
126         my $path = $rel_path =~ m{^/} ? $rel_path : "$pwd/$rel_path";
127
128         warn "$hostname [$command] $on_host:$path | $message\n";
129
130         my $args_message = $message;
131
132         $message ||= "$path [$command]";
133         $message = "$hostname: $message";
134
135         my $dir = $path;
136         $dir =~ s{/[^/]+$}{};
137
138         my $backup_path = -e "$hostname/$path" ? "$hostname/$path" : $hostname;
139
140         sub git {
141                 my $args = join(' ',@_);
142                 warn "# git $args\n";
143                 my $out = `git $args`;
144                 warn "$out\n# [", length($out), " bytes]\n" if defined $out;
145                 return $out;
146         }
147
148         if ( ! $command ) {
149                 pull_changes $hostname;
150         } elsif ( $command eq 'add' ) {
151                 mkpath "$hostname/$dir" unless -e "$hostname/$dir";
152                 while ( $path ) {
153                         rsync( '-avv', "root\@$hostname:$path", "$hostname/$path" );
154                         print $client git 'add', "$hostname/$path";
155
156                         $args_message =~ s/^(.+)\b// || last;
157                         $path = $1;
158                         warn "? $path";
159                 }
160         } elsif ( $command eq 'commit' ) {
161                 pull_changes $hostname;
162                 $message =~ s/'/\\'/g;
163                 $user =~ s/\/$//;
164                 print $client git( "commit -m '$message' --author '$user <$hostname>' $backup_path" );
165         } elsif ( $command =~ m{(diff|status|log|ch)} ) {
166                 $command .= ' --stat' if $command eq 'log';
167                 $command = 'log --patch-with-stat' if $command =~ m/^ch/;
168                 pull_changes( $hostname ) if $command eq 'diff';
169                 if ( $on_host ) {
170                         mkpath "$hostname/$dir" unless -e "$hostname/$dir";
171                         rsync( '-avv', "root\@$hostname:$path", "$hostname/$path" );
172                         rsync( '-avv', "root\@$on_host:$path", "$on_host/$path" );
173                         open(my $diff, '-|', "diff -Nuw $hostname$path $on_host$path");
174                         while(<$diff>) {
175                                 print $client $_;
176                         }
177                 } else {
178                         # commands without path will show host-wide status/changes
179                         my $backup_path = $path ? "$hostname/$path" : "$hostname/";
180                         # hostname must end with / to prevent error from git:
181                         # ambiguous argument 'arh-hw': both revision and filename
182                         # to support branches named as hosts
183                         print $client git($command, $backup_path);
184                 }
185         } elsif ( $command eq 'revert' ) {
186                 if ( $on_host ) {
187                         rsync( '-avv', "$on_host/$path", "root\@$hostname:$path" );
188                 } else {
189                         print $client git "checkout -- $hostname/$path";
190                         rsync( '-avv', "$hostname/$path", "root\@$hostname:$path" );
191                 }
192         } elsif ( $command eq 'cat' ) {
193                 my $file_path = ( $on_host ? $on_host : $hostname ) . "/$path";
194                 open(my $file, '<', $file_path) || warn "ERROR $file_path: $!";
195                 while(<$file>) {
196                         print $client $_;
197                 }
198                 close($file);
199         } else {
200                 print $client "Unknown command: $command\n";
201         }
202
203 }
204