#!/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


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
    """
    if vm.protocol == "SSH":
        arguments = ("-ssh -P %s -pw %s" % (vm.port, vm.password)
                     + "%s@%s" % (vm.user, vm.host))
        subprocess.Popen("putty.exe "+arguments, shell=True)
    elif vm.protocol == "NX":
        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
                    break
        if not found:
            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()
        subprocess.Popen(config_file, shell=True)
    elif vm.protocol == "RDP":
        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
                    break
        if not found:
            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()
        subprocess.Popen(config_file, shell=True)


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"""