#!/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);

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

mkdir $dir if ! -e $dir;

unlink $log_fifo if -e $log_fifo;
mkfifo $log_fifo, 0700;

sub kill_rsync {
	return unless -e $pid_file;
	my $pid = read_file $pid_file;
	warn "kill_rsync $pid_file = $pid";
	kill 2, $pid && warn "kill INT $pid old rsync server";
	kill 0, $pid && unlink $pid_file && warn "removed $pid_file";
}

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 %o %u %h %a %m %l %f
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";

kill_rsync;
sub DESTROY { kill_rsync; };

my $exec = "rsync --daemon --config $cfg_file --no-detach --port=6501";

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

warn "START $exec\n";
open(my $rsync_fd, '-|', $exec);

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";
	}
	close($log);
	sleep 1;
}

