#!/usr/bin/python

import os
import sys
import subprocess
from keystoneclient import session
from keystoneclient.v3 import client
from keystoneclient.auth.identity import v3
from keystoneauth1 import exceptions

CONFIG_DIR = "/usr/share/guest-tools-cloudinit/"
CONFIG_TOOLS_WIN = CONFIG_DIR + "disk_config_tools_win.xml"
CONFIG_TOOLS_LIN = CONFIG_DIR + "disk_config_tools_lin.xml"


def keystone_connect():
    '''
    Try connection to keystone
    '''
    try:
        auth_url = os.environ['OS_AUTH_URL']
        username = os.environ['OS_USERNAME']
        project_name = os.environ['OS_PROJECT_NAME']
        password = os.environ['OS_PASSWORD']

    except KeyError:
        print ('The following environment variables should be set:' '\n'
                'auth_url''\n'
                'username''\n'
                'project_name''\n'
                'password''\n'
                'You can also initialise it by run following command:' '\n'
                'kolla-ansible -i /etc/kolla/inventory post-deploy && source /etc/kolla/admin-openrc.sh' '\n')
        sys.exit(1)

    try:
        global keystone
        auth = v3.Password(auth_url=auth_url,
                        username=username,
                        project_name=project_name,
                        password=password,
                        user_domain_id='default',
                        project_domain_id='default')
        sess = session.Session(auth=auth,verify=False)
        keystone = client.Client(session=sess,insecure=True)
        print ("Using user_domain_id='default'" '\n'
            "Using project_domain_id='default'")

    except keystoneauth1.exceptions.http.Unauthorized as ee:
        print ('Connection error')
        sys.exit(1)
    return 
    
def prepare_cloud(domain_name):
    '''
    Get volume id of instance, make cloud-config.iso and xml.
    '''
    from novaclient import client
    from novaclient.v2 import volumes
    from novaclient import base
    
    nova = client.Client(2, session=keystone.session)
    instances = {}

    try:
        server_list = nova.servers.list()
    except exceptions.http.Unauthorized as ee:
        print ('Connection error to keystone (HTTP 401)')
        sys.exit(1)

    for instance in server_list:
        instances[instance] = instance.name,instance.id
    
    for i in instances:
        serv_name = instances[i][0]
        serv_ids =  instances[i][1]
        if domain_name in serv_name:
            vol_ids = str(nova.volumes.get_server_volumes(serv_ids))
            vp = vol_ids.split()[1]
            vp = vp[:-2]
            prepare_cloud_iso(vp,os_type)
	    vv = prepare_xml_cloud(vp)
	    return vv
    return None

def prepare_cloud_iso(vp,os_type):
    if 'linux' in os_type:
        p = subprocess.Popen("python /usr/libexec/cloud_config_ctl.py --format cloud-init --datastore /usr/share/vz-guest-tools/vz-lin-user-config --output-iso /mnt/vstorage/volume-%s/cloud-config.iso merge"%(vp),shell=True)
        p.communicate()
    elif 'windows' in os_type:
        p = subprocess.Popen("python /usr/libexec/cloud_config_ctl.py --format cloudbase-init --datastore /usr/share/vz-guest-tools/vz-win-user-config --output-iso /mnt/vstorage/volume-%s/cloud-config.iso merge"%(vp),shell=True)
        p.communicate()


def prepare_xml_cloud(vp):
    xml = ("<disk type='file' device='cdrom'>" '\n'
    '\t'"<driver name='qemu' type='raw' cache='none' io='native' discard='unmap'/>" '\n'
    '\t'"<source file='/mnt/vstorage/volume-%s/cloud-config.iso'/>" '\n'
    '\t'"<target dev='hda' bus='ide'/>" '\n'
    '\t'"<readonly/>" '\n'
    '\t'"<address type='drive' controller='0' bus='0' target='0' unit='0'/>'" '\n'
        "</disk>" %(vp))
    path = os.path.join ('/tmp/disk_config_cloud_' + vp + '.xml')
    with open(path, 'w') as f:
        f.write(xml)
    return path

        
def main (domain_name,os_type):
    if 'linux' in os_type:
        keystone_connect()
        vv = prepare_cloud(domain_name)
        config = vv
        p = subprocess.Popen("virsh attach-device %s --config %s" %(domain_name,config) ,shell=True)
        p.communicate()
        config = CONFIG_TOOLS_LIN
        p = subprocess.Popen("virsh attach-device %s --config %s" %(domain_name,config) ,shell=True)
        p.communicate()   
               
        
    elif 'windows' in os_type:
        keystone_connect()
        vv = prepare_cloud(domain_name)
        config = vv
        p = subprocess.Popen("virsh attach-device %s --config %s" %(domain_name,config) ,shell=True)
        p.communicate()
        config = CONFIG_TOOLS_WIN
        p = subprocess.Popen("virsh attach-device %s --config %s" %(domain_name,config) ,shell=True)
        p.communicate()
    return

if __name__ == "__main__":
    try:
        domain_name = sys.argv[1]
        os_type = sys.argv[2]
    except:
        print ('\n' "Usage: hci-install-guest [domain] [linux|windows]")
        sys.exit(1)
    
    main (domain_name,os_type)


