#!/usr/bin/perl
use warnings;
use strict;

use autodie;
use POSIX;
use File::Slurp;
use IO::Select;
use Time::HiRes;
use Data::Dump qw(dump);
use English;

my $dir = '/srv/cloudstore/var';
my $log_fifo = "$dir/rsyncd.log";
my $pid_file = "$dir/rsyncd.pid";
my $cfg_file   = "$dir/rsyncd.conf";
my $users    = "users";

mkdir $dir if ! -e $dir;

mkfifo $log_fifo, 0700 unless -p $log_fifo;

my $transfer_log = {
	ip => '%a',
	user => '%u',
	host => '%h',
	perms => '%B',
	file => '%f',
	updated => '%i',
	len => '%l',
	transfered => '%b',
	module => '%m',
	mtime => '%M',
	op => '%o',
	pid => '%p',
	timestamp => '%t',
};

my $rsync_config = qq{

#uid = nobody
#gid = nogroup
#use chroot = yes
use chroot = no

#max connections = 4
lock file = $dir/rsyncd.lock

#syslog facility = local5
log file  = $log_fifo

transfer logging = yes
log format = transfer-log:} . join('|',values %$transfer_log) . qq{
max verbosity = 5

pid file  = $pid_file

# don't check secrets file permission (uid)
strict modes = no

pre-xfer exec = /srv/cloudstore/pre-xfer.sh
post-xfer exec = /srv/cloudstore/post-xfer.sh

[dpavlin]
	path = /srv/cloudstore/users/dpavlin/blob
	auth users = dpavlin
	secrets file = /srv/cloudstore/secrets/dpavlin
	read only = false

};

write_file $cfg_file, $rsync_config;
warn "created $cfg_file ", -s $cfg_file, " bytes\n";

if ( -e $pid_file ) {
	my $pid = read_file $pid_file;
	chomp($pid);
	if ( kill 0, $pid ) {
		warn "found rsync pid $pid";
	} else {
		unlink $pid_file;
	}
}

if ( ! -e $pid_file ) {
	my $exec = "rsync --daemon --config $cfg_file --no-detach --port=6501";
	warn "START $exec\n";

	die "could not fork\n" unless defined(my $pid = fork);
	unless ($pid) {
		warn "start server with $exec\n";
		exec $exec || die $!;
	}

	warn "wait for pid file";
	while ( ! -e $pid_file ) {
		sleep 1;
	}
}


while(1) {
	warn "# reading log output from $log_fifo\n";
	open(my $log, '<', $log_fifo);
	while( my $line = <$log> ) {
		print "LINE: $line";
		if ( $line =~ /transfer-log:(.+\|.+)/ ) {
			my %data;
			my @k = keys %$transfer_log;
			my @v = split(/\|/,$1);
			@data{@k} = @v ; # FIXME validate?
			print "transfer-log:",dump(\%data),$/;
		}
	}
	close($log);
	sleep 1;
}

