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

    This script is Zone aware, and loops through share configuration in
    a per zone manner

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

    Dump information:
        Global config
        Open sessions
        Open files
        For each zone:
            Default share config for the zone
            For each share in the zone:
                Share info

'''

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

# 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.smb.shares.util as shares_util
import controllers.isi.smb.settings.util as settings_util
import controllers.isi.smb.sessions.util as sessions_util
import controllers.isi.smb.openfiles.util as openfiles_util
import controllers.isi.smb.shares.permission.util as perm_util
import controllers.isi.smb.util as smb_util

# 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

URI_ZONES = '/3/zones'
GLOBAL_SETTINGS_PATH = "/3/protocols/smb/settings/global"
SHARE_SETTINGS_PATH = "/3/protocols/smb/settings/share"
SESSIONS_LIST_PATH = "/1/protocols/smb/sessions"
OPENFILES_PATH = "/1/protocols/smb/openfiles"
SHARES_PATH = "/3/protocols/smb/shares"

H_BREAK = 44


def print_header(title, cmd):
    print '-' * H_BREAK
    print " %s: '/usr/bin/isi --timeout=15 smb %s'" % (title, cmd)
    print '-' * H_BREAK

def print_failure(failure, cmd):
    print " /usr/bin/isi smb %s failed: %s" % (cmd, failure)

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 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']

    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_zones():
    '''
    Retrieve information about all available zones.  Return value is an
    array zones.
    '''

    try:
        response = papi.get(URI_ZONES)
        check_papi_response(response, 'get_zones: ')

        zones = []
        for zone in response.body['zones']:
            zones.append(zone)
    except Exception as err:
        print ' /usr/bin/isi zone list failed: %s' % err
        zones = [{'name': 'System'}]

    return zones


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 global_settings():
    '''
        Get the global smb settings from papi and print.
    '''
    print_header('Global Settings', 'settings global view')

    try:
        uri = GLOBAL_SETTINGS_PATH
        params = {'scope': 'effective'}
        response = papi.get(uri, params)
        check_papi_response(response, 'global_settings: ')

        fmt = pl.PropertyListFormatter(headers=settings_util.global_options)
        fmt.render(response.body.get('settings'))
    except Exception as err:
        print_failure(err, 'settings global view')


def open_sessions():
    '''
        Get all open sessions and print. Use the callback to reduce memory usage
    '''
    def print_sessions(sessions, first, last):
        '''
            Callback when a set of results is returned from papi. Only print
            the header when it is the first set of results. Only print the
            footer if it is the last set of results
        '''
        fmt = views.factory.formatter('table',
                                      headers=sessions_util.smb_session_headers(True),
                                      show_headers=first,
                                      verbose=False,
                                      footer=last)

        fmt.render(sessions)

    print_header('Open Sessions', 'sessions list')

    try:
        uri = SESSIONS_LIST_PATH
        count = get_all(uri, 'sessions', print_sessions)
        print_totals(count)
    except Exception as err:
        print_failure(err, 'sessions list')

def open_files():
    '''
        Get all open files and print. Use the callback to reduce memory usage
    '''
    def print_files(files, first, last):
        '''
            Callback when a set of results is returned from papi. Only print
            the header when it is the first set of results. Only print the
            footer if it is the last set of results
        '''
        fmt = views.factory.formatter('table',
            headers=openfiles_util.smb_openfiles_headers(),
            show_headers=first,
            verbose=False,
            footer=last)

        fmt.render(files)

    print_header('Open Files', 'openfiles list')

    try:
        uri = OPENFILES_PATH
        count = get_all(uri, 'openfiles', print_files)
        print_totals(count)
    except Exception as err:
        print_failure(err, 'openfiles list')

def print_shares(zonename='System'):
    '''
        Get all shares and print. Use the callback to reduce memory usage
    '''
    def callback(shares, first, last):
        '''
            Callback when a set of results is returned from papi. Only print
            the header when it is the first set of results. Only print the
            footer if it is the last set of results
        '''
        for share in shares:
            # basic share info
            sharename = share.get('name')

            print_header("(%s) Share '%s'" % (zonename, sharename),
                    "shares view %s --zone=%s" % (sharename, zonename))

            fmt = pl.PropertyListFormatter(headers=
                    shares_util.smb_view_headers())
            fmt.render(share)

            # permissions
            data = {}
            data[sharename] = share
            print "Permissions:"
            pcontroller = perm_util.PermissionsController(data, sharename)
            fmt = table.TabularFormatter(headers=
                                         shares_util.smb_view_table_headers())
            fmt.render(pcontroller.permissions_table())
            print
            # headers
            fmt = pl.PropertyListFormatter(headers=
                        shares_util.smb_view_settings_headers())
            fmt.render(share)
            print

    try:
        uri = SHARES_PATH
        count = get_all(uri, 'shares', callback, {'zone': zonename, 'resolve_names': True})
        print_totals(count)
    except Exception as err:
        print_failure(err, 'shares list -v')


def print_zone(zone):
    '''
        Using the zone info, get the default share and print it off
    '''
    print_header('Zone \'%s\'' % zone.get('name'),
                'settings shares view --zone=%s' % zone.get('name'))

    try:
        uri = SHARE_SETTINGS_PATH
        response = papi.get(uri)
        check_papi_response(response, 'share_settings: ')

        fmt = pl.PropertyListFormatter(headers=settings_util.shares_options)
        fmt.render(response.body.get('settings'))
    except Exception as err:
        print_failure(err, 'settings shares view --zone=%s' % zone.get('name'))


def main(args):
    global_settings()
    open_sessions()
    open_files()

    zones = get_zones()

    for zone in zones:
        print_zone(zone)
        print_shares(zone.get('name'))

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