#!/usr/bin/perl -sw
#$version = "1.00";

# Created by Steve Voisey (srv) 21 Jan 2011.
# email: [steve.voisey@ericsson.com]

#use Regexp::Common qw/net/;
#if ($hashValue =~ /($RE{net}{ipv4})/) {

# Just see IP's
# ./rpt.pl | tr -s " " | cut -d " " -f2

my $defaultDir = "/opt/tandbergtv/cms/scripts/install";
my $sep = ",";
my $replaceSep = "(comma)";

#my $tokenRegExp = "\.[0-9]+?\.[0-9]+?\.[0-9]+?\.[0-9]+?";
my $tokenRegExp = "\.[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+";
my %masterHash;

unless(defined($print))  {$print = "master"; }
unless(defined($format)) { $format = "screen"; }

unless (defined($list))  {
    $list = "default";
    print "define list\n";
    @defaultTokenListFiles = ("ta.vienna.production.token.list",
                             "ta.vienna.test01.token.list",
                             "uk.dev2.token.list");
} else {
    @defaultTokenListFiles = split(',',"$list");
}

if ($list =~ /^all$/i) {
    print "all: $defaultDir/*.token.list\n";
    @defaultTokenListFiles = <$defaultDir/*.token.list>;
}


foreach $file (@defaultTokenListFiles) {
    my %tokenHash;
    print "\nfile: $file\n";

    unless (-f "$defaultDir/$file")      { die "invalid file: $defaultDir/$file"; }
    unless (open (TOKEN, "<$defaultDir/$file"))  { die "cannot open $defaultDir/$file $!"; }
    @tokenArray = <TOKEN>;
    close TOKEN;
    @tokenArray = removeComments(\@tokenArray);
    %tokenHash  = buildConfigHash(\@tokenArray);
    buildMasterConfigHash(\%masterHash,\%tokenHash,$file);
    if ( $print =~ m/ip/i ) {
        print "print: IP-HASH\n\n";
        print "==== ==== ==== ====";
        printTokenIpValues(\%tokenHash);
    }
}

if ( $print =~ m/master/i ) {
    print "\nprint: MASTER-HASH\n\n";
    print "==== ==== ==== ====";
    printTokenValues(\%masterHash, $format);
}



exit;

#########################################################################
#########################################################################

sub removeComments {
    my $fileArrayRef = $_[0];
    my @newArray;
    my $line;
    # print "\n\n+++++++++++ removeComments +++++++++++++\n";
    foreach $line (@$fileArrayRef) {
        chomp($line);
        # Just in case we have come from windows, make sure we don't have any <CR> left in the line.
        $line =~ s/\r//g;
        # Drop the comments.
        if ($line =~ /^#/) { next; }
        # Drop any blank lines.
        if ($line =~ /^\s*$/) { next; }
        # print "[$line]\n";
        push(@newArray,"$line");
    }
    return @newArray;
}

#########################################################################
#########################################################################

sub buildConfigHash {
  # Convert a list of "x=y" values, into a hash.
  my $symArrayRef = $_[0];
  my %configHash;
  my $element = "";
  my @tmp = "";
  # Need to clean up each entry, strip out comments, spaces...
  foreach $element (@$symArrayRef) {
    # Split into two fields 'x=y'
    @tmp = split ('=',$element,2);
    # Any undefined values, set to "" and print a warning.
    unless (defined($tmp[1])) { $tmp[1] = ""; print "\nWARNING: original: $tmp[0] No setting defined!!!\n\n" }
    chomp($tmp[1]);
    # Just in case we have come from windows, make sure we don't have any <CR> at end of the TOKEN
    $tmp[1] =~ s/\r//g;
    # Build a hash db with our setting=value pair.
    if (defined($configHash{$tmp[0]})) {
        #print "\nWARNING: Duplicate setting for [ $tmp[0] ]\n";
        #print "FIRST VALUE: $configHash{$tmp[0]}\n";
        #print "REPLACED BY: $tmp[1]\n\n";
    }
    $configHash{$tmp[0]} = $tmp[1];
  }
  return %configHash;
}

#########################################################################
#########################################################################

sub printTokenValues {
    my $tokenHashRef = $_[0];
    my $format       = $_[1];

    unless(defined($format)) { $format = "screen"; }

    my $hashValue = "";
    my @tokenKeys = sort(keys(%$tokenHashRef));

    foreach $key (@tokenKeys) {
        $hashValue = $$tokenHashRef{$key};
        if ( $format =~ m/screen/i ) {
            printf "%-45s --> $hashValue\n", $key;
        }
        if ( $format =~ m/csv/i ) {
            printf "${key}${sep}${hashValue}\n";
        }
    }
}

#########################################################################
#########################################################################

sub printTokenIpValues {
    my $tokenHashRef = $_[0];
    #my $ipOnly       = $_[1];
    my $hashValue = "";
    my %ipHash;

    my $ValidIpAddressRegex = "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+";
    #my $ValidIpAddressRegex = "\\d+\\.\\d+\\.\\d+\\.\\d+";
    #my $ValidIpAddressRegex = "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])";
    #my $ValidIpAddressRegex = "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.{3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])";
    #my $ValidIpAddressRegex = "[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]\\.{3}[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]";

    my @tokenKeys = sort(keys(%$tokenHashRef));

    foreach $key (@tokenKeys) {
        $hashValue = $$tokenHashRef{$key};
        if ($hashValue =~ m/$ValidIpAddressRegex/) {
           ($ip) = ($hashValue =~ m/($ValidIpAddressRegex)/);
            unless(defined($ipHash{$ip})) {
                #printf "%-45s --> [$bit] $ip  --> $hashValue\n", $key;
                printf "%-16s %-45s --> $hashValue\n", $ip, $key;
                $ipHash{$ip} = $hashValue;
            }
        }

    }
}

#########################################################################
#########################################################################

sub buildMasterConfigHash {
    # Convert a list of "x=y" values, into a hash.
    my $masterHashRef = $_[0];
    my $hashRef       = $_[1];
    my $file          = $_[2];
    my %templateHash;
    my @tmp = "";


    unless(defined($$masterHashRef{"#2-COLUMN-HEAD"})) { $$masterHashRef{"#2-COLUMN-HEAD"} = ""; }
    $$masterHashRef{"#2-COLUMN-HEAD"} = $$masterHashRef{"#2-COLUMN-HEAD"} . $file . $sep;
    unless(defined($$masterHashRef{"#2-ENTRY-COUNT"})) { $$masterHashRef{"#1-COLUMN-HEAD"} = 0; }
    $$masterHashRef{"#1-COLUMN-HEAD"} = $$masterHashRef{"#1-COLUMN-HEAD"} + 1;
    #$tmp = $$masterHashRef{'#1-COLUMN-HEAD'};

    $empty     = "${sep}";
    $emptyList = $empty x ($$masterHashRef{'#1-COLUMN-HEAD'} - 1);

    #print "file: $file emptyList: $emptyList\n";

    my @masterHashKeys = sort(keys(%$masterHashRef));
    # initialize the template with all keys, but no values.
    foreach $key (@masterHashKeys) { $templateHash{$key} = ""; }

    my @tokenKeys = sort(keys(%$hashRef));
    # Add the values of current hash.
    foreach $key (@tokenKeys) {
        $$hashRef{$key} =~ s/$sep/$replaceSep/g;
        if(defined($templateHash{$key})) {
            $templateHash{$key} = $$hashRef{$key};
        } else {
            if ( $$masterHashRef{"#1-COLUMN-HEAD"} > 1 ) {
                 $templateHash{$key} = $emptyList . $$hashRef{$key};
            } else {
                 $templateHash{$key} = $$hashRef{$key};
            }
        }
    }

    my @templateHashKeys = sort(keys(%templateHash));
    foreach $key (@templateHashKeys) {
        if ( $key =~ m/^#/ ) { next; }
        if(defined($$masterHashRef{$key})) {
            $$masterHashRef{$key} = $$masterHashRef{$key} . $sep . $templateHash{$key};
        } else {
            $$masterHashRef{$key} = $templateHash{$key};
        }
    }
}


exit;

