#!/usr/bin/env python
#coding=utf8

'''
CloudControl CLI
'''

import os, os.path
import sys
import cccli
from cccli import printer,cli
import optparse
import ConfigParser
import pprint
import re
import warnings
import getpass

settings = {}
alias = {}

try:
    # parse rc file
    if "HOME" in os.environ and  os.access("%s/.cc-cli.conf"%os.environ["HOME"], os.R_OK):
        fparser = ConfigParser.SafeConfigParser()
        fparser.read("%s/.cc-cli.conf"%os.environ["HOME"])
        if fparser.has_section("cli"):
            settings = dict(fparser.items("cli"))
        if fparser.has_section("alias"):
            alias = dict(fparser.items("alias"))

    # parse env
    if "CC_SERVER" in os.environ:
        settings["server"] = os.environ["CC_SERVER"]
    if "CC_PORT" in os.environ:
        settings["port"] = os.environ["CC_PORT"]
    if "CC_LOGIN" in os.environ:
        settings["login"] = os.environ["CC_LOGIN"]
    if "CC_DEBUG" in os.environ:
        settings["debug"] = "True"

    # Parse line argument
    oparser = optparse.OptionParser(usage="usage: %prog [options] [server[:port]]",
                                    version=cccli.version)
    oparser.add_option("-d", "--debug",
                       action="store_true",
                       dest="debug",
                       default=False,
                       help="debug mode")
    oparser.add_option("-l", "--login",
                       action="store",
                       dest="login",
                       default="",
                       help="server login")
    (options, args) = oparser.parse_args()

    # show usage if no default conf and no server given
    if len(settings) == 0 and len(args) == 0:
        oparser.print_help()
        sys.exit(1)

    # debug option handling
    if options.debug or "debug" in settings:
        cccli.debug = True

    # args handling
    if len(args) == 1:
        sargs = args[0].split(":", 1)
        if len(sargs) > 1:
            settings["port"] = sargs[1]
        if not sargs[0] == "":
            settings["host"] = sargs[0]

    # remove password to prevent it showing
    if "pass" in settings:
        del settings["pass"]

    # debug stuff
    if cccli.debug:
        printer.err("Debugging on")
        printer.err("Settings: %s"%settings)
        printer.err("Alias: %s"%alias)
    else:
        warnings.filterwarnings("ignore")

    # checking needs
    if settings["server"] == "":
        raise Exception("Invalid server name/ip")
    try:
        settings["port"] = int(settings["port"])
    except:
        raise Exception("Invalid port number")

    # asking for login
    if settings["login"] == "":
        settings["login"] = raw_input("Login: ")

    # asking for password
    settings["pass"] = getpass.getpass("Password: ")

    # start cli
    cli = cli.Cli(settings, alias)
    cli.run()
except KeyboardInterrupt:
    exit(1)
except Exception, e:
    if cccli.debug:
        printer.fatal(str(e), exitcode=-1)
        raise
    printer.fatal(str(e))
