
import os
import codecs
from appPublic.log import debug, error, exception
from appPublic.folderUtils import temp_file
from appPublic.sshx import SSHNode
from sqlor.dbpools import DBPools
from .getdbname import get_dbname

async def write_client_key(prikey):
	client_key = temp_file()
	with codecs.open(client_key, 'w', 'utf-8') as f:
		f.write(host.client_key)
	return client_key

	
async def _gethostdev(sor, hostid):
	sql1 = """select a.*, b.enterhostid from hostdev a, devgroup b 
where a.id=${id}$ 
	and a.devgroupid = b.id"""
	sql = """
select x.*, 
	y.host as jhost,
	y.port as jport,
	y.user as juser,
	y.ssh_method as jssh_method,
	y.passwd as jpassword,
	y.client_key as jclient_key,
	y.passphrase as jpassphrase
from (""" + sql1 + """) a left join hostdev b
	on a.enterhostid = b.id
"""
	recs = await sor.sqlExe(sql, {'id':hostid})
	if len(recs) == 0:
		return None
	return rec[0]

async def hostdev_node(hostid, sor=None):
	host = None
	if sor:
		host = await _gethostdev(sor, hostid)
	else:
		db = DBPools()
		dbname = get_dbname()
		async with db.sqlorContext(dbname) as sor:
			host = await _gethostdev(sor, hostid)
	jumpers = []
	jclient_key = None
	client_key = None
	node = None
	if host.jssh_method == '0':
		jumper = {
			'host':host.jhost,
			'port':host.jport,
			'username':host.juser,
			'password':host.jpassword
		}
		jumpers.append(jumper)
	else:
		jclient_key = write_client_key(host.jclient_key)
		jumper = {
			'host':host.jhost,
			'port':host.jport,
			'client_keys': [ client_key ],
			'passphrase': jhost.passphrase
		}
		jumpers.append(jumper)

	if host.ssh_method == '0':		# password
		node = SSHNode(host.host,
				username=host.user,
				port=host.port or 22,
				password=host.passwd,
				jumpers=jumpers)
	else:
		client_key = write_client_key(host.client_key)
		node = SSHNode(host.host,
				username=host.user,
				port=host.port or 22,
				client_keys=[client_key],
				passphrase=host.passphrase,
				jumpers=jumpers)
	if jclient_key:
		node.jclient_key_file = jclient_key
	if client_key:
		node.client_key_file = client_key
	return node

