#!/usr/bin/perl

use strict;
use Getopt::Long;
use Pod::Usage;
use Lemonldap::NG::Common::Conf;
use Lemonldap::NG::Common::Conf::Constants qw(
  DEFAULTCONFBACKEND
  DEFAULTCONFBACKENDOPTIONS
);

my %opts;
my $result = GetOptions( \%opts, 'help|h', 'current|c=s', 'new|n=s', 'latest|l',
    'overwrite|o', 'force|f' );

pod2usage(0) if $opts{help};

# Previous behavior when setting --current and --new was to always overwrite
$opts{overwrite} = 1 if ( $opts{current} and $opts{new} );

# If current config not provided, fallback to default config storage
my $old;
if ( $opts{current} ) {
    unless ( -r $opts{current} ) {
        print STDERR $opts{current} . " is not readable\n";
        exit 3;
    }

    $old = Lemonldap::NG::Common::Conf->new( {
            confFile => $opts{current},
        }
    );
}
else {
    $old = Lemonldap::NG::Common::Conf->new( {
            type => DEFAULTCONFBACKEND,
            DEFAULTCONFBACKENDOPTIONS,
        }
    );
}
unless ($old) {
    print STDERR
      "Failed to get current conf : $Lemonldap::NG::Common::Conf::msg\n";
    exit 4;
}

my %newargs = (
    force       => 1,
    noCache     => 1,
    cfgNumFixed => 1,
);

# If new config not provided, fallback to currently configured backend
my $new;
if ( $opts{new} ) {
    unless ( -r $opts{new} ) {
        print STDERR $opts{new} . " is not readable\n";
        exit 3;
    }
    $new = Lemonldap::NG::Common::Conf->new( {
            confFile => $opts{new},
        }
    );
}
else {
    $new = Lemonldap::NG::Common::Conf->new;
}

unless ($new) {
    print STDERR
      "Failed to create new conf object : $Lemonldap::NG::Common::Conf::msg\n";
    exit 5;
}

my $oldtype = $old->{type} =~ s/^Lemonldap::NG::Common::Conf::Backends:://r;
my $newtype = $new->{type} =~ s/^Lemonldap::NG::Common::Conf::Backends:://r;
print STDERR "Converting from " . $oldtype . " to " . $newtype . "\n";

if ( $oldtype eq $newtype ) {
    print STDERR "\nWARNING: "
      . "converting configuration without changing backend type.\n"
      . "Make sure you know what you are doing.\n\n";
}

my @available;
if ( $opts{latest} ) {
    @available = $old->lastCfg();
}
else {
    @available = $old->available();
}

my @dstavailable = $new->available();

# Compute intersection of src and dst config numbers
my %tmp;
foreach my $e ( @available, @dstavailable ) { $tmp{$e}++ }
my @isect = grep { $tmp{$_} > 1 } keys %tmp;

if ( @isect and not $opts{overwrite} ) {
    print STDERR "WARNING: " . @isect
      . " existing configurations found in destination \n";
    print STDERR "    use --overwrite to overwrite existing configurations\n";
    exit 8;
}

foreach (@available) {
    my $conf = $old->getConf( { cfgNum => $_, noCache => 1 } );
    unless ($conf) {
        print STDERR
          "\nFailed to get conf $_ : $Lemonldap::NG::Common::Conf::msg\n";
        next if ( $opts{force} );
        exit 6;
    }
    if ( my $r = $new->saveConf( $conf, %newargs ) ) {
        print "Conf $conf->{cfgNum} stored\n";
        next;
    }
    print STDERR
"Unable to store configuration $conf->{cfgNum}: $Lemonldap::NG::Common::Conf::msg";
    next if ( $opts{force} );
    exit 7;
}

__END__

=head1 NAME

=encoding utf8

convertConfig - A tool to migrate Lemonldap::NG configuration database to a new backend.

=head1 SYNOPSIS

=over 14

=item B<convertConfig>
[B<--help>]
[B<--current>S< >I</old/lemonldap-ng.ini>]
[B<--new>S< >I</new/lemonldap-ng.ini>]
[B<--latest>]
[B<--overwrite>]
[B<--force>]

=item Convert from default B<File> backend to the currently configured backend

B<convertConfig>

=item Convert only the latest config (configuration history is lost)

B<convertConfig> B<--latest>

=item Specify different INI config files containing old or new backends

B<convertConfig> B<--current>S< >I<config> B<--new>S< >I<config>

=item Continue even if an error occurs

B<convertConfig> B<--force>

=back

=head1 DESCRIPTION

convertConfig is a command line tool to convert all configurations stored
in database and initialize a new Lemonldap::NG configuration based on
current configuration.

=head1 SEE ALSO

L<http://lemonldap-ng.org/>

=head1 AUTHORS

=over

=item Clement Oudot, E<lt>clem.oudot@gmail.comE<gt>

=item Xavier Guimard, E<lt>x.guimard@free.frE<gt>

=back

=head1 BUG REPORT

Use OW2 system to report bug or ask for features:
L<https://gitlab.ow2.org/lemonldap-ng/lemonldap-ng/issues>

=head1 DOWNLOAD

Lemonldap::NG is available at
L<https://lemonldap-ng.org/download>

=head1 COPYRIGHT AND LICENSE

=over

=item Copyright (C) 2008-2016 by Xavier Guimard, E<lt>x.guimard@free.frE<gt>

=item Copyright (C) 2008-2016 by Clément Oudot, E<lt>clem.oudot@gmail.comE<gt>

=back

This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see L<http://www.gnu.org/licenses/>.

=cut
