from config import *
from xml.etree import ElementTree as ET
from flask import request, Response
import os

def get_vnc_port(vm_name):
    dom = conn.lookupByName(vm_name)
    vm_xml = dom.XMLDesc(0)
    et_xml = ET.fromstring(vm_xml)
    graphics = et_xml.find('./devices/graphics')
    vnc_port = graphics.get('port')
    return vnc_port

def kill_consoles():
    os.system('kill -9 $(ps -edf | grep websockify | grep -v grep | awk \'{ print $2 }\')')
    os.system('for i in $(ps -edf | grep pyxterm | grep -v grep | awk \'{ print $2 }\');do kill -9 $i;done')

def socket_connect(vm_name):
    kill_consoles()
    vm_port = get_vnc_port(vm_name)
    os.system('websockify -D --web=/usr/share/novnc/ 6080 localhost:'+vm_port)

def pyxterm_connect(path,lxc_name):
    kill_consoles()
    os.system('python3 '+path+'/pyxterm.py --command \'lxc-attach\' --cmd-args \''+lxc_name+'\' &')
