#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Configuration of the Windows specific tools to enhance the ease of use
of the CIRCLE cloud. Handles the auto launch and auto configuration
of these specific connectivity programs.
"""

import time
import os
import subprocess
import glob
import win32crypt
import binascii
import nxkey
import logging


def connect(vm):
    """
    Handles to connection to the Virtual Machines from the local
    machine

    Keyword arguments:
    vm.protocol -- SSH, NX and RDP possible
    vm.host     -- Address of the Virtual Computer
    vm.port     -- The port where we can access the Virtual Computer
    vm.user     -- Username used for the connection
    vm.password -- Password used for the connection
    """
    logger = logging.getLogger()
    logger.info('Connect methods started')
    if vm.protocol == "SSH":
        logger.debug('SSH protocol received')
        arguments = ("-ssh -P %(port)s -pw %(password)s"
                     " %(user)s@%(host)s" % {
                         'port': vm.port,
                         'password': vm.password,
                         'user': vm.user,
                         'host': vm.host})
        directory = os.path.dirname(os.path.abspath(__file__))
        logger.debug('Popen: %s\\putty.exe', directory)
        logger.info('Determined arguments: %s', arguments)
        subprocess.Popen("%(path)s\\putty.exe %(arguments)s" % {
            'path': directory,
            'arguments': arguments}, shell=True)
    elif vm.protocol == "NX":
        logger.debug('NX protocol received')
        listdir = os.path.expanduser("~\\.nx\\config\\*.nxs")
        found = False
        server = "\"Server host\" value=\"%s\"" % vm.host
        port = "\"Server port\" value=\"%s\"" % vm.port
        for config_file in glob.glob(listdir):
            with open(config_file) as f:
                file = f.read()
                if server in file and port in file:
                    found = True
                    logger.info('Config file found: %s', config_file)
                    break
        if not found:
            logger.info('No config file found, creating new one')
            config_file = "%s%s%s" % (os.path.expanduser("~\\.nx\\config\\"),
                                      str(int(time.time() * 1000)), ".nxs")
            password = nxkey.NXKeyGen(vm.password).getEncrypted()
            config = NX_template % {'USERNAME': vm.user, 'PASSWORD': password,
                                    'HOST': vm.host, 'PORT': vm.port}
            f = open(config_file, 'w')
            f.write(config)
            f.close()
            logger.info('Config file created: %s', config_file)
        logger.debug('Popen the config file: %s', config_file)
        subprocess.Popen(config_file, shell=True)
    elif vm.protocol == "RDP":
        logger.debug('NX protocol received')
        listdir = os.path.dirname(os.path.realpath(__file__)) + "\\.rdp\\*.rdp"
        found = False
        full_address = "full address:s:%s:%s" % (vm.host, vm.port)
        user = "username:s:%s" % vm.user
        for config_file in glob.glob(listdir):
            with open(config_file) as f:
                file = f.read()
                if full_address in file and user in file:
                    found = True
                    logger.info('Config file found: %s', config_file)
                    break
        if not found:
            logger.info('No config file found, creating new one')
            config_file = "%s%s%s" % ((os.path.dirname(
                os.path.realpath(__file__)) + "\\.rdp\\"),
                str(int(time.time() * 1000)), ".rdp")
            password = binascii.hexlify(win32crypt.CryptProtectData(
                u"%s" % vm.password, u'psw', None, None, None, 0))
            config = RPD_template % {'USERNAME': vm.user, 'PASSWORD': password,
                                     'HOST': vm.host, 'PORT': vm.port}
            f = open(config_file, 'w')
            f.write(config)
            f.close()
            logger.info('Config file created: %s', config_file)
        logger.debug('Popen the config file: %s', config_file)
        subprocess.Popen(config_file, shell=True)
    logger.info('Client finished working')

NX_template = """<!DOCTYPE NXClientSettings>
<NXClientSettings application="nxclient" version="1.3" >
<group name="General" >
<option key="Remember password" value="true" />
<option key="Resolution" value="fullscreen" />
<option key="Server host" value="%(HOST)s" />
<option key="Server port" value="%(PORT)s" />
<option key="Session" value="unix" />
</group>
<group name="Login" >
<option key="Auth" value="%(PASSWORD)s" />
<option key="Guest Mode" value="false" />
<option key="Login Method" value="nx" />
<option key="User" value="%(USERNAME)s" />
</group>
</NXClientSettings>"""

RPD_template = """username:s:%(USERNAME)s
full address:s:%(HOST)s:%(PORT)s
password 51:b:%(PASSWORD)s"""
