#!/usr/bin/perl

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

##########################################################################
# Copyright (c) 2010-2012 Alexander Bluhm <alexander.bluhm@gmx.net>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
##########################################################################

use strict;
use warnings;
use Getopt::Long qw(:config posix_default bundling);
use OSPF::LSDB::Cisco;
use OSPF::LSDB::YAML;

sub usage(@) {
    print STDERR "Error: @_\n" if @_;
    print STDERR <<EOF;
Convert Cisco OSPF link state database to YAML file.  If the show
ip ospf content files are not given on the command line, ssh is
invoked to log into the router.

Usage: $0 [-h] [-B boundary] [-E external] [-H user\@host]
  [-I selfid] [-N network] [-R router] [-S summary] [ospf.yaml]
    -h           help, print usage
    -B boundary  file containg output of 'show ip ospf database asbr-summary'
    -E external  file containg output of 'show ip ospf database external'
    -H user\@host use user\@host for ssh login
    -I selfid    file containg output of 'show ip ospf summary'
    -N network   file containg output of 'show ip ospf database network'
    -R router    file containg output of 'show ip ospf database router'
    -S summary   file containg output of 'show ip ospf database summary'
    ospf.yaml    output file, default stdout
EOF
    exit(2);
}

sub main() {
    my(%files, $ssh);
    GetOptions(
	'h'   => sub { usage() },
	'B=s' => \$files{boundary},
	'E=s' => \$files{external},
	'H=s' => \$ssh,
	'I=s' => \$files{selfid},
	'N=s' => \$files{network},
	'R=s' => \$files{router},
	'S=s' => \$files{summary},
    ) or usage("Bad option");
    usage("Only one arguments allowed") if @ARGV > 1;

    my $cisco = OSPF::LSDB::Cisco->new(ssh => $ssh);
    $cisco->parse(%files);

    my $yaml = OSPF::LSDB::YAML->new($cisco);
    if (@ARGV > 0) {
	$yaml->DumpFile($ARGV[0]);
    } else {
	print $yaml->Dump();
    }
}

main();
