#!/usr/bin/env python
'''
    Wrapper script to gather all necessary network data from the "isi network" CLI

    This script is groupnet aware, and loops through subnets/pools/etc for each
    groupnet

    This prints all network data by spoofing the CLI so we utilize data that is
    returned from papi calls in order to speed up data gather

    Dump information:
        Dump SmartConnect state (goes to seperate file)
        External Network settings
        DNS Cache Settings
        Open files
        For each groupnet:
            print groupnet
            for each subnet
                print subnet
                for each pool
                    print pool
                    for each rule:
                        print rule

'''

import sys
import getopt
import json
import traceback
import isi.papi.basepapi as papi
import subprocess
import time

# add cli to python path for this script. Does not modify path outside this file
sys.path.append("/usr/local/share/CLI")

#import modules from isi CLI
import views.factory
import views.propertylist as pl
import views.table as table
import controllers.isi.network.util as util_network
import controllers.isi.network.subnets.util as util_subnet
import controllers.isi.network.pools.util as util_pool
import controllers.isi.network.rules.util as util_rules
import controllers.isi.network.interfaces.util as util_interfaces
import controllers.isi.network.groupnets.util as util_groupnet
import controllers.isi.network.external.util as util_external
import controllers.isi.network.dnscache.util as util_dnscache

# Exception class definitions
class OptionError(getopt.GetoptError): pass
class OptionInvalidCombinationError(OptionError): pass
class OptionUnmetRequirementError(OptionError): pass
class PapiResponseError(Exception): pass
class PapiResponse400Error(PapiResponseError): pass
class PapiResponse500Error(PapiResponseError): pass

DNS_CACHE_SETTINGS_PATH = "/4/network/dnscache"
EXTERNAL_SETTINGS_PATH =  "/4/network/external"
GROUPNET_SETTINGS_PATH =  "/4/network/groupnets"
SUBNETS_SETTINGS_PATH =   "/4/network/subnets"
INTERFACES_PATH =         "/4/network/interfaces"
RULES_SETTINGS_PATH =     "/4/network/rules"

H_BREAK = 44


def print_header(title):
    print '-' * H_BREAK
    print " %s" % title
    print '-' * H_BREAK

def print_totals(total):
    '''
    if it is split into multiple segments,the total wont be right, so print
    the correct total
    '''
    if total is not 0:
        print "Total: %d" % total

def dump_smartconnect_state():
    print_header("Dumping Cluster-Wide SmartConnect State")

    try:
        subprocess.call(["/usr/bin/isi_for_array", "-X", "pkill -WINCH isi_dnsiq_d"])
        # wait for dump
        time.sleep(10)
        subprocess.call(["/usr/bin/isi_for_array", "-S", "-Q",
            "echo `ls -t /var/log/isi_smartconnect_state* | head -n1`; "\
            "cat `ls -t /var/log/isi_smartconnect_state* | head -n1`; sleep 5"])
        print "\t Done"
    except Exception as e:
        print "\t Failed: %s" % e
        pass

def check_papi_response(response, prefix=''):
    '''
    Utility function which raises an exception for all 400 and 500
    family HTTP status codes.
    '''

    if response.status >= 400:
        error_string =  prefix + '\n  ' + response.headers['status'] + '\n  '
        error_string += response.body['errors'][0]['message']
        print error_string

    if response.status >= 400 and response.status <= 499:
        raise PapiResponse400Error(error_string)
    elif response.status >= 500 and response.status <= 599:
        raise PapiResponse500Error(error_string)

def get_groupnets(groupnet=None):
    '''
    Retrieve information about a specific groupnet or enumerate all
    available groupnets.  Return value is an array zones.
    '''
    uri = GROUPNET_SETTINGS_PATH
    if groupnet is not None:
        uri = uri + '/' + groupnet

    response = papi.get(uri)
    check_papi_response(response, 'get_groupnets: ')

    groupnets = []
    for groupnet in response.body['groupnets']:
        groupnets.append(groupnet)

    return groupnets

def get_subnets(subnet=None, groupnet="~DEFAULT"):
    uri = "/4/network/groupnets/{0}/subnets".format(groupnet)

    if subnet is not None:
        uri = uri + '/' + subnet

    response = papi.get(uri)
    check_papi_response(response, 'get_subnets: ')

    subnets = []
    for subnet in response.body['subnets']:
        subnets.append(subnet)

    return subnets

def get_pools(subnet, pool=None, groupnet="~DEFAULT"):
    uri = "/4/network/groupnets/{0}/subnets/{1}/pools".format(groupnet, subnet)

    if pool is not None:
        uri = uri + '/' + pool

    response = papi.get(uri)
    check_papi_response(response, 'get_pools: ')

    pools = []
    for pool in response.body['pools']:
        pools.append(pool)

    return pools

def get_rules(subnet, pool, rule=None, groupnet="~DEFAULT"):
    uri = "/4/network/groupnets/{0}/subnets/{1}/pools/{2}/rules".format(groupnet, subnet, pool)

    if rule  is not None:
        uri = uri + '/' + rule

    response = papi.get(uri)
    check_papi_response(response, 'get_rules: ')

    rules = []
    for rule in response.body['rules']:
        rules.append(rule)

    return rules

def get_all(uri, key, callback=None, params={}):
    '''
        For requests that might return a resume token, continue making calls
        while a resume token is returned. If a callback is passed, use it to
        avoid holding all results.

        Return value:
            if no callback, return all the results in an array
            otherwise, returns a count of how many results were processed
    '''
    done = False
    resume = None
    first = True
    results = []
    count = 0

    while done is False:
        response = papi.get(uri, args=params)
        check_papi_response(response, uri)

        resume = response.body.get('resume', None)
        count += response.body.get('total', 0)

        for result in response.body.get(key, []):
            results.append(result)

        if resume is None:
            done = True

        if callback is not None:
            # pass first/done so table formatting is correct
            callback(results, first, done)
            del results
            results = []

        first = False

        # resume token will remember arguments, so dont send again
        params = {}

        if resume is not None:
            params['resume'] = resume

    if callback is not None:
        return count
    else:
        return results


def external_settings():
    '''
        Get the external network settings from papi and print.
    '''
    uri = EXTERNAL_SETTINGS_PATH
    response = papi.get(uri)
    check_papi_response(response, 'external_settings: ')

    print_header('External Network Settings')

    fmt = pl.PropertyListFormatter(headers=util_external.external_view_opts())
    fmt.render(response.body.get('settings'))

def dnscache_settings():
    '''
        Get the dnscache network settings from papi and print.
    '''
    uri = DNS_CACHE_SETTINGS_PATH
    response = papi.get(uri)
    check_papi_response(response, 'external_settings: ')

    print_header('DNS Cache Network Settings')

    fmt = pl.PropertyListFormatter(headers=util_dnscache.dnscache_opts())
    fmt.render(response.body.get('settings'))

def print_groupnet(groupnet):
    '''
        Using the groupnet info, get the groupnet settings and print them off
    '''
    print_header('Groupnet \'%s\'' % groupnet.get('id'))
    fmt = pl.PropertyListFormatter(headers=util_groupnet.grpnet_headers())
    fmt.render(groupnet)

def print_subnet(subnet):
    '''
        Using the subnet info, get the subnet settings and print them off
    '''
    print_header('Subnet \'%s\'' % subnet.get('id'))
    fmt = pl.PropertyListFormatter(headers=util_subnet.subnet_headers(verbose=True))
    fmt.render(subnet)

def print_pool(pool):
    '''
        Using the pool info, get the pool settings and print them off
    '''
    print_header('Pool \'%s\'' % pool.get('id'))
    fmt = pl.PropertyListFormatter(headers=util_pool.pools_view_headers())
    fmt.render(pool)

def print_rule(rule):
    '''
        Using the rule info, get the rule settings and print them off
    '''
    print_header('Rule \'%s\'' % rule.get('id'))
    fmt = pl.PropertyListFormatter(headers=util_rules.rule_headers(verbose=True))
    fmt.render(rule)

def main(args):
    try:
        dump_smartconnect_state()
        external_settings()
        dnscache_settings()

        groupnets = get_groupnets()

        for groupnet in groupnets:
            print_groupnet(groupnet)
            subnets = get_subnets(groupnet=groupnet.get('name'))

            for subnet in subnets:
                print_subnet(subnet)
                pools = get_pools(groupnet=groupnet.get('name'),
                    subnet=subnet.get('name'))

                for pool in pools:
                    print_pool(pool)
                    rules = get_rules(groupnet=groupnet.get('name'),
                        subnet=subnet.get('name'), pool=pool.get('name'))

                    for rule in rules:
                        print_rule(rule)

    except Exception as err:
        print err

if __name__ == '__main__':
    # Default to an unknown error
    retcode = 127
    try:
        retcode = main(sys.argv[1:])
    finally:
        sys.exit(retcode)
