#!/usr/local/bin/perl

our %CONF;
BEGIN {
    %CONF = ( version => '20101123.01',
              homedir => '/home/hostedsites/lbconfig',
            );
    unshift( @INC, ("$CONF{homedir}/data/lib") );
};

use strict;
use A10::AX;
use Data::Dumper;

open(CONFIG, "$CONF{homedir}/data/config") || die "cannot read $CONF{homedir}/data/config: $!\n";
while(<CONFIG>){
    s/#.*//g;
    next if(/^\s*$/);
    my($hname,$hcolo,$hzone,$hcolor,$hun,$hpw) = split /:/;
    $CONF{hosts}{$hname} = { zone => $hzone, color => $hcolor, colo => $hcolo, un => $hun, pw => $hpw };
}
close CONFIG;

for my $host ( sort { $a cmp $b || $a <=> $b } keys %{$CONF{hosts}} ){
    my $ax      = A10::AX->new(conf => \%CONF, host => $host);
    my $servers = $ax->api('slb.server.getAll');
    #print Dumper $servers;
    #exit;
    my $groups  = $ax->api('slb.service-group.getAll');
    my $vips    = $ax->api('slb.vip.getAll');
    my $stat    = $ax->api('slb.server.fetchAllStatistics');

    my %aton;
    for my $server (keys %{$servers->{servers}{server}}){
        $aton{ $servers->{servers}{server}{$server}{address} } = $server;
    }

    my $virt = $vips->{'virtual-servers'}->{'virtual-server'};
    for my $virtname (keys %{$virt}){
        my $status  = $virt->{$virtname}{status};
        my $address = $virt->{$virtname}{address};       
        my $servref = $virt->{$virtname}{services}{service};

        # stupid API isnt consistent
        my $saref = ( ref($servref) eq 'ARRAY' ) ? $servref : [ $servref ];

        print "vip $virtname\n",
              " |-> status: [$status] ", $ax->status($status), "\n",
              " |-> address: $address\n";
        for my $service ( @{$saref} ){
            print " |-> port: $service->{port}\n",
                  " +-> gname: $service->{service_group}\n",
                  "      |-> status: ", $ax->status($service->{status}), "\n",
                  "      |-> type:   ", $ax->type($service->{type}), "\n";

            # members of this group
            my $memref = $groups->{'service-groups'}{'service-group'}{ $service->{service_group} }{members}{member};
            my $maref = ( ref($memref) eq 'ARRAY') ? $memref : [ $memref ];
            
            for my $member ( @{$maref} ){
                print "      +-> member: ", $aton{ $member->{address} }, "\n",
                      "           |-> address: $member->{address}\n",
                      "           |-> port: $member->{port}\n",
                      "           |-> weight: $member->{weight}\n",
                      "           |-> priority: $member->{priority}\n",
                      "           +-> status: ", $ax->status($member->{status}), "\n";
            }
        }
    }
    $ax->close;
}
