#!/usr/bin/perl
#===============================================================================
#      PODNAME:  net_cidr_lite_merge.pl
#     ABSTRACT:  use Net::CIDR::Lite to merge nets from ARGV, STDIN or file
#
#       AUTHOR:  Reid Augustin
#        EMAIL:  reid@LucidPort.com
#      CREATED:  10/12/2014 05:53:55 PM
#===============================================================================

use 5.008;
use strict;
use warnings;
use utf8;

use open qw( :utf8 :std );  # UTF8 for all files and STDIO
use IO::File;
use File::Spec;
use Readonly;
use Getopt::Long qw(:config pass_through);  # for GetOptions(...)
use Net::CIDR::Lite;
use Net::IP::Identifier::Regex;

our $VERSION = '0.086'; # VERSION

my (undef, undef, $myName) = File::Spec->splitpath($0);

my $file;
my $verbose = 0;

exit 0 if (not
    GetOptions(
        'file=s'   => \$file,
        'verbose' => \$verbose,
    )
);

if (@ARGV and
    not $file and
    -f $ARGV[0]) {
    $file = shift @ARGV;
}

my $fh;
if ($file) {
    open $fh, '<', $file or die "failed to open $file for reading: $!\n";
}
elsif (@ARGV) {
    require IO::String;
    my @args;
    for my $ii (0 .. $#ARGV) {
        my $arg = $ARGV[$ii];
        if (($arg eq '-' or $arg eq '+')    # allow two types of net range with spaces
            and @args
            and $ii < @ARGV) {
            $args[-1] .= "$arg$ARGV[++$ii]";
        }
        else {
            push @args, $arg;
        }
    }
    $fh = IO::String->new(join "\n", @args)
}
else {
    $fh = *STDIN;
}

my $re = Net::IP::Identifier::Regex->new;
my $re_ip = $re->IP_any;
my $cidr = Net::CIDR::Lite->new;

while (defined (my $line = $fh->getline)) {
    my @nets = $line =~ m/\b($re_ip)\b/g;
    map { $cidr->add_any($_) } @nets;
}

my $list = $cidr->list;

for my $net (@{$list}) {
    print "$net\n";
}

__END__

=pod

=encoding UTF-8

=head1 NAME

net_cidr_lite_merge.pl - use Net::CIDR::Lite to merge nets from ARGV, STDIN or file

=head1 VERSION

version 0.086

=head1 AUTHOR

Reid Augustin <reid@hellosix.com>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2014 by Reid Augustin.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
