#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell

use strict;
use warnings;
use Pod::Usage;
use MMM::MirrorList;
use Getopt::Long;

=head1 NAME

mmm_list - mmm mirror manager list editor

=head1 SYNOPSIS

    mmm_list <listfile> [<action> ...]
    mmm_list <listfile> list
    mmm_list <listfile> add <source> <url> [<level> [<frequency>]]

=head1 DESCRIPTION

A tools to easilly add mirror into mirror list.

The first argument is the mirror list to edit. The file is created if it does
not exists.

The source name defined the content of the mirror, ensure the name is the
proper one.

=cut

GetOptions(
    'p|password=s' => \my $password,
    's|ssh' => \my $ssh,
) or pod2usage();

$ARGV[0] or pod2usage();

my $mml = MMM::MirrorList->new();
if (-f $ARGV[0]) {
    $mml->load_list($ARGV[0]);
}

for ($ARGV[1] || 'list') {
    /^list$/ and do {
        foreach my $source ($mml->list_sources) {
            print "> $source:\n";
            foreach ($mml->mirrors($source)) {
                printf "\t%s\n", $_->info;
            }
        }
        last;
    };

    /^add$/ and do {
        $ARGV[3] or pod2usage();
        $mml->add_mirror(
            {
                url => $ARGV[3],
                level => $ARGV[4],
                frequency => $ARGV[5],
                password => $password,
                ssh => $ssh,
            },
            $ARGV[2]
        );
        if (open(my $h, '>', $ARGV[0])) {
            print $h $mml->xml_output;
            close($h);
        } else {
            die "Cannot open $ARGV[0]\n";
        }
        last;
    };

    warn "unknow command $_\n";
    pod2usage();
}

__END__

=head1 AUTHOR

Olivier Thauvin <nanardon@nanardon.zarb.org>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2006 Olivier Thauvin

This program 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
of the License, 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

=cut
