#!/usr/bin/perl -w
#
# Simple wrapper for jpilot-sync, because jpilot-sync -l is so goddamn buggy.
#
# Copyright (c) 2005 Andrew Dolgov <cthulhoo@gmail.com>
#
# GPL, etc.
#

use strict;

use IO::Socket;
use Socket;

use Fcntl ':flock';

my $pid_handle;
my $pid_file = "/tmp/hotsyncd-" . $ENV{"USER"} . ".pid";

my $port = 14237;
my $sock;
my $command = "jpilot-sync";

print " * hotsyncd/0.1 starting\n";

print " * checking pidfile\n";
	
open $pid_handle, ">$pid_file" or die " * ERROR: can't create pidfile ($pid_file): $!\n";
	
if (! flock($pid_handle, LOCK_EX | LOCK_NB)) {
	die " * ERROR: can't lock pidfile: another daemon is running?";
     exit 4;
}

print $pid_handle "$$\n";
autoflush $pid_handle 1;

$SIG{'INT'} = sub {
	print " * received SIGINT: closing socket and exiting\n";
	close $sock;	
	unlink $pid_file;
	exit 3;
};

while (1) {
 		
	print " * binding to port $port\n";

	$sock = IO::Socket::INET->new(LocalPort => $port, 
				Proto => 'udp', 
				ReuseAddr => 1);

	if (!$sock) {
		print " * ERROR: can't bind to socket: $!\n";
		exit 2;
	}
	
	print " * waiting for client connection\n";

	my $buf;
	
	if ($sock->recv($buf, 1)) {
		print " * handling client connection\n";
		close $sock;
		system($command);
	}
	
	sleep 1;
}


