#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;
use Pod::Usage;
use LATMOS::Accounts;
use LATMOS::Accounts::Log;

GetOptions(
    'nodaemon' => \my $nodaemon,
    'c|config=s'   => \my $config,
    'help'         => sub { pod2usage(0) },
    'test'         => \my $test,
    's|syncname=s' => \my $syncname,
) or pod2usage();

my $needsync = 0;
my $pidfile = undef;

$SIG{'HUP'} = sub {
    $needsync = 1;
};

la_set_log(
    syslog => [],
    console => ($nodaemon ? LA_NOTICE : undef),
);

{
    my $LA = LATMOS::Accounts->new($config, noacl => 1);
    if ($LA->val('_default_', 'state_dir')) {
        $pidfile = $LA->val('_default_', 'state_dir') . '/sync-manager.pid';
    }
}

# Daemonize
if (!$nodaemon) {
    my $pid = fork;
    if ($pid) {
        exit 0;
    }
}

$SIG{INT} = sub {
    unlink($pidfile) if ($pidfile);
    exit 0;
};

if ($pidfile) {
    # maybe we want to lock here !!
    open(my $fh, '>', $pidfile) or die "Cannot open pidfile $pidfile\n";
    print $fh "$$\n";
    close($fh);
}

sub sync {

    la_log LA_NOTICE, "Starting synchronisation";
    my $LA = LATMOS::Accounts->new($config, noacl => 1) or do {
        la_log LA_ERR, "Cannot instantiate LA";
        return 1;
    };

    my $sync = $LA->create_synchro(
        $syncname || $LA->default_synchro_name,
        test     => $test,
    ) or do {
       la_log LA_ERR, "cannot create sync object";
       return 2;
    };

    $sync->load_dest and do {
        la_log LA_ERR, "Cannot load destination";
        return 3;
    };

    $sync->process() or do {
        la_log LA_ERR, "Sync has failed\n";
        return 4;
    };
    la_log LA_NOTICE, "Ending synchronisation";

    return 0;
}

while (1) {
    if ($needsync) {
        $needsync = 0;
        my $pid = fork;
        if ($pid == 0) {
	    $SIG{INT} = undef;
            exit sync();
        } else {
            while(waitpid($pid, 0) <= 0) {}
            my $res = $? << 8;
            if ($res) {
               la_log LA_ERR, "Sync process exit with $res";
           } 
        }
        next;
    }

    # waiting, to perform next sync
    sleep(60 * 15);
    $needsync = 1;
}

