#!/usr/bin/perl

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

=head1 NAME

    la-sync - Tools to synchronize base

=head1 SYNOPSIS

Show configured bases:

    la-sync [options]

=cut

GetOptions(
    'c|config=s'   => \my $config,
    'help'         => sub { pod2usage(0) },
    'from=s'       => \my $from,
    'to=s'         => \my @to,
    'nocreate'     => \my $nocreate,
    'nodelete'     => \my $nodelete,
    'test'         => \my $test,
    'o|object=s'   => \my $otype,
    's|syncname=s' => \my $syncname,
    'b|batch'      => \my $batch,
    'unexp'        => \my $unexp,
) or pod2usage();

=head1 OPTIONS

=over 4

=item -c|--config configdir

Use this configuration directory instead of the default one.

=item --from basename

Specify source base to use

=item --to basename

Specify destination base to use, this option can be used
severals times

=item --nocreate

Don't create object, synchronize existing

=item --test

Don't change anything, just test

=item -s|--syncname name

Use synchronisation named C<name> in configuration instead default

=item -o|object object_type

Query will be performed on this object. Default is the 'User' object.

=item -b|--batch

Don't really perform any synchronisation but try to call daemon process
to perform immediate synchronisation. 

=item --unexp

Sync unexported objects in source base

=back

=cut

my $LA = LATMOS::Accounts->new($config, noacl => 1);

if ($batch) {
    warn "Using la-sync -b is deprecated, use la-sync-ctl -s instead\n";
    exit ($LA->call_batch_sync ? 0 : 1);
}

my $sync = $LA->create_synchro(
    $syncname,
    from => $from,
    to => (@to ? [ @to ] : undef),
    test     => $test,
    unexported => $unexp,
) or die "cannot create sync object\n";
$sync->load_dest and return;
if ($otype) {
    foreach (@ARGV) {
        warn "Try to sync $otype: $_\n";
        $sync->sync_object($otype, $_, onepass => 1) or do {
	    warn "Error while synching $_ ($otype)\n";
	    exit 1;
        }
    }
} else {
    $sync->process(
    	test     => $test,
    	nodelete => $nodelete,
    	nocreate => $nocreate,
    ) or warn "Sync has failed\n";
}

exit 0;
