#!python

from __future__ import print_function

import getopt
import sys
import nsgcli.nsgcli_main


usage_msg = """
Interactive NetSpyGlass control script. This script can only communicate with 
NetSpyGlass server running on the same machine.

Usage:

    nsgcli.py --base-url=url [--token=token] [--network=netid] [--region=region] [command]
    
    --base-url:  server access URL without the path, for example 'http://nsg.domain.com:9100'
                 --base-url must be provided.
    --token:     server API access token (if the server is configured with user authentication)
    --region:    if present, all commands will be executed on given region. Equivalent to the command 'region' in
                 the interactive mode.

    all arguments provided on the command line after the last switch are interpreted together as nsgcli command
"""


class InvalidArgsException(Exception):
    pass


def usage():
    print(usage_msg)


if __name__ == '__main__':

    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   'hs:b:t:n:r:',
                                   ['help', 'base-url=', 'token=', 'network=', 'region='])
    except getopt.GetoptError as ex:
        print('UNKNOWN: Invalid Argument:' + str(ex))
        raise InvalidArgsException

    base_url = ''
    token = ''
    netid = 1
    region = None
    command = ''

    for opt, arg in opts:
        if opt in ['-h', '--help']:
            usage()
            sys.exit(3)
        elif opt in ('-b', '--base-url'):
            base_url = arg.rstrip('/ ')
        elif opt in ('-a', '--token'):
            token = arg
        elif opt in ('-n', '--network'):
            netid = arg
        elif opt in ['-r', '--region']:
            region = arg

    if args:
        command = ' '.join(args)

    script = nsgcli.nsgcli_main.NsgCLI(base_url=base_url, token=token, netid=netid, region=region)
    script.make_prompt()

    if command:
        script.onecmd(command)
        sys.exit(0)
    else:
        script.summary()
        # script.prompt = ' > '
        # script.ping()
        script.cmdloop()
