#!python


import getopt
import os
import sys

import nsgcli.nsgcli_main
import nsgcli.response_formatter
import nsgcli.sub_command
from nsgcli.version import __version__

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 [-a|-t|--token=token] [--network=netid] [--region=region] [-U|--utc] [-L|--local]
               [--agent-prefix=auto|always|never] [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.
    --utc:       print values in the column `time` in ISO 8601 format in UTC
    --local:     print values in the column `time` in ISO 8601 format in local timezone (default)
    --agent-prefix:  prefix each line of agent command output with the name of the agent that replied.
                 'auto' (default) does this only when the reply may come from more than one agent
                 (commands 'exec ...', 'agent all ...', 'agent find ...'), 'always' and 'never' override.
    -v, --version:   print version and exit

    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:a:t:n:r:LUv',
                                   ['help', 'local', 'utc', 'base-url=', 'token=', 'network=', 'region=', 'version',
                                    'agent-prefix='])
    except getopt.GetoptError as ex:
        print('UNKNOWN: Invalid Argument:' + str(ex))
        raise InvalidArgsException

    base_url = os.getenv('NSG_SERVICE_URL')
    token = os.getenv('NSG_API_TOKEN')
    netid = 1
    region = None
    command = ''
    time_format = nsgcli.response_formatter.TIME_FORMAT_ISO_LOCAL
    agent_prefix = nsgcli.sub_command.AGENT_PREFIX_AUTO

    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', '-t', '--token'):
            token = arg
        elif opt in ('-n', '--network'):
            netid = arg
        elif opt in ['-r', '--region']:
            region = arg
        elif opt in ['-U', '--utc']:
            # prints time in ISO format in UTC
            time_format = nsgcli.response_formatter.TIME_FORMAT_ISO_UTC
        elif opt in ['-L', '--local']:
            # prints time in ISO format in local time zone
            time_format = nsgcli.response_formatter.TIME_FORMAT_ISO_LOCAL
        elif opt == '--agent-prefix':
            if arg not in nsgcli.sub_command.AGENT_PREFIX_MODES:
                print('--agent-prefix must be one of: ' + ', '.join(nsgcli.sub_command.AGENT_PREFIX_MODES))
                sys.exit(3)
            agent_prefix = arg
        elif opt in ['-v', '--version']:
            print(__version__)
            sys.exit(0)

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

    if not base_url:
        print('--base-url parameter is mandatory')
        raise InvalidArgsException

    if token is None:
        token = ''

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

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