#!/usr/bin/env python

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

URI_SHARES='/3/protocols/smb/shares'
URI_ZONES='/3/zones'

# 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


#  Functions
def print_usage():
    '''
    Print the general command usage to stadout
    '''

    print (
        '''Usage: {0} [--enable-ca|--disable-ca] [--all|--share=<sharename>] [--zone=<zonename>]

Configure an existing share to either enable or disable SMB3
continuous availablity support.  Making a change here will delete and
recreate the share, resulting in a disconnection for all current
clients.

    --all                 Recreate all shares (optionally for a specific --zone)
    --disable-ca          Recreate a share to disable CA functionality
    --enable-ca           Recreate a share to enable CA functionality
    --share=<share name>  Specify the share name to recreate
    --help                Print command usage summary
    --verify              Perform additional verification to ensure the
                          recreate share matches the original definition
    --zone=<zone name>    Specifiy the zone containing the share(s)
                          (Default: 'System')
'''.format(sys.argv[0]))


def parse_args(args):
    '''
    Parse all command line arguements with error checking.  Also
    verify valid option combinations.

    '''

    short_opts = ''
    long_opts = [ 'help', 'enable-ca', 'disable-ca', 'all', 'share=', 'verify', 'zone=' ]

    (options, values) = getopt.gnu_getopt(args, short_opts, long_opts)
    if len(values) > 0:
        raise OptionError('Unknown trailing parameter(s): \"{0}\"'.format(str(values)))

    opts = {}
    for (o, v) in options:
        opts[o] = v

    if opts.has_key('--enable-ca') and opts.has_key('--disable-ca'):
        raise OptionInvalidCombinationError('Cannot enable and disable CA concurrently!')

    if not opts.has_key('--enable-ca') and not opts.has_key('--disable-ca'):
        raise OptionInvalidCombinationError('Must specify either to enable and disable CA!')

    if opts.has_key('--all') and opts.has_key('--share'):
        raise OptionInvalidCombinationError('Cannot specify all shares and a specific share concurrently!')

    if not opts.has_key('--all') and not opts.has_key('--share'):
        raise OptionUnmetRequirementError('Missing requirement to process a specific shares or all shares')

    if opts.has_key('--share') and not opts.has_key('--zone'):
        opts['--zone'] = 'System'

    return opts

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 and response.status <= 499:
        error_string = prefix + '\n  ' + response.headers['status'] + '\n  ' + response.body['errors'][0]['message']
        raise PapiResponse400Error(error_string)
    elif response.status >= 500 and response.status <= 599:
        error_string = prefix + '\n  ' + response.headers['status'] + '\n  ' + response.body['errors'][0]['message']
        raise PapiResponse500Error(error_string)

def get_zones(zonename=None):
    '''
    Retrieve information about a specific zone or enumerate all
    available zones.  Return value is a dictinary of id to name
    mappings.
    '''

    uri = URI_ZONES
    if zonename is not None:
        uri += '/' + zonename

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

    zone_ids = {}
    for zone in response.body['zones']:
        zone_ids[zone['zone_id']] = zone['name']

    return zone_ids

def enumerate_shares(zonename):
    '''
    Enumerate all existing shares within a specified zone.  Return
    value is an array of tuples where each tupple contains the
    sharename and zonename.

    '''

    resume = None
    done = False
    sharenames = []
    uri = URI_SHARES

    while done is False:
        args = {'zone': zonename}
        if resume is not None:
            args = { 'resume': resume }

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

        resume = response.body['resume']

        for share in response.body['shares']:
            sharenames += [(share['name'], zonename)]

        if resume is None:
            done = True

    return sharenames

def get_share(sharename, zonename):
    '''
    Retrieve the complete information for the specified share and zone.
    Returned dictionary is the share JSON payload with the query-only
    fields replaced (id and zid).
    '''

    uri = URI_SHARES + '/' + sharename
    share_info = {}

    response = papi.get(uri, args={'zone' : zonename, 'scope' : 'user'})
    check_papi_response(response, 'get_share: ')

    share_info = response.body['shares'][0]
    share_info['name'] = sharename
    share_info['zone'] = zonename
    share_info.pop('id')
    share_info.pop('zid')

    return share_info

def delete_share(sharename, zonename):
    '''
    Remove a share from the specified zone.
    '''

    uri = URI_SHARES + '/' + sharename

    response = papi.delete(uri, args={'zone' : zonename})

def create_share(shareinfo):
    '''
    Create a new share from the spefied dictionary body.
    '''

    uri = URI_SHARES

    response = papi.post(uri=uri, body=shareinfo, args={'zone' : shareinfo['zone']})
    check_papi_response(response, 'create_share: ')


def shareinfo_equal(share1, share2):
    '''
    Compares the dictionary between two shares and returns a dictionary
    of any differences.   Returns True is the two shares match and False
    otherwise.
    '''

    diff_keys = set(share1.keys()) ^ set(share2.keys())
    if len(diff_keys) != 0:
        return False

    for k in share1.keys():
        if type(share1[k]) is not type(share2[k]):
            print ('{0}: {1} type is not {2}'.format(k, share1[k], share2[k]))
            return False
        elif type(share1[k]) is dict and not shareinfo_equal(share1[k], share2[k]):
            print ('{0}: {1} dictionary value doe not match {2}'.format(k, share1[k], share2[k]))
            return False
        elif share1[k] != share2[k]:
            print ('{0}: {1} != {2}'.format(k, share1[k], share2[k]))
            return False

    return True

def main(args):
    '''
    Main program driver.
    '''

    retcode = 0

    try:
        options = parse_args(args)
    except getopt.GetoptError as e:
        print ('{0}\n'.format(str(e)))
        print_usage()
        return 1

    if options.has_key('--help'):
        print_usage()
        return 0

    try:
        zones = get_zones(None if not options.has_key('--zone') else options['--zone']);
    except Exception as e:
        print ('{0}\n'.format(str(e)))
        return 1

    shares = []
    if options.has_key('--all'):
        for k in zones.keys():
            try:
                zone_shares = enumerate_shares(zones[k])
            except Exception as e:
                print ('{0}\n'.format(str(e)))
                return 1
            shares += zone_shares
    else:
        shares = [ (options['--share'], options['--zone']) ]

    enable_ca = True if options.has_key('--enable-ca') else False

    print ('Recreating shares to {0} continuous availability...'.
           format('enable' if enable_ca else 'disable'))

    for (sharename, zonename) in shares:
        sys.stdout.write('Share \"{0}\" (zone: {1})...'.format(sharename, zonename))
        sys.stdout.write('retrieving...')
        try:
            shareinfo = get_share(sharename, zonename)
        except PapiResponseError as e:
            print ('Failed to retrieve share \"{0}\": \"{1}\"'.format(sharename, e))
            retcode = 1
            continue

        share_ca = shareinfo.get('continuously_available', None)

        if share_ca != enable_ca:
            sys.stdout.write('removing...')
            try:
                delete_share(sharename, zonename)
            except PapiResponseError as e:
                print ('Failed to delete original share \"{0}\": \"{1}\"'.format(sharename, e))
                print (json.dumps(shareinfo, indent=4))
                retcode = 1
                continue

            shareinfo['continuously_available'] = enable_ca

            sys.stdout.write('recreating...')
            try:
                create_share(shareinfo)
            except PapiResponseError as e:
                print ('Failed to recreate the share \"{0}\": \"{1}\"'.format(sharename, e))
                print (json.dumps(shareinfo, indent=4))
                retcode = 1
                # Something is wrong -- Avoid further damage
                break

            if options.has_key('--verify'):
                sys.stdout.write('verifying...')
                try:
                    shareinfo2 = get_share(sharename, zonename)
                except PapiResponseError as e:
                    print ('Failed to retrieve new share \"{0}\": \"{1}\"'.format(sharename, e))
                    retcode = 1
                    # Cannot verify if we can't compare -- Avoid further potential damage
                    break

                if shareinfo_equal(shareinfo, shareinfo2) is False:
                    print ('{0}: old and new shareinfo do not match!'.format(shareinfo['name']))
                    retcode = 1
                    # Break out now -- Avoid further potential damage
                    break

        else:
            sys.stdout.write('no change needed...')

        sys.stdout.write('done\n')

    return retcode


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