#!/usr/bin/python3
#
# Copyright 2024 RED SOFT
#
# Author: Anton Fadeev <anton.fadeev@red-soft.ru>
#
#


from __future__ import absolute_import

import os
import sys
import hooking
import traceback
import json

TD_QC = '''
["-device", "ich9-intel-hda",\
"-device", "hda-duplex",\
"-device", "nec-usb-xhci,id=xhci",\
"-device", "usb-host,hostbus=2,hostport=3,id=usb23",\
"-spice", "jpeg-wan-compression=always", \
"-device", "virtio-serial",\
"-chardev", "spiceport,id=WebDavPort,name=org.spice-space.webdav.0",\
"-chardev", "socket,path=/tmp/termidesk/tvmd.sock,server=off,reconnect=1,mux=on,id=ru_termidesk_tvm",\
"-device", "virtserialport,chardev=ru_termidesk_tvm,name=ru.termidesk.tvm.0",\
"-chardev", "spiceport,id=RealtimeStreamingPort,name=TDSK_STREAM",\
"-device", "virtserialport,chardev=RealtimeStreamingPort,name=ru.termidesk.RealtimeStreaming.0",\
"-chardev", "spiceport,id=PrinterPort,name=TDSK_PRINTER",\
"-device", "virtserialport,chardev=PrinterPort,name=ru.termidesk.Printer.0",\
"-chardev", "spiceport,id=SmardCardPort,name=TDSK_PCSC",\
"-device", "virtserialport,chardev=SmardCardPort,name=ru.termidesk.PCSC.0"]
'''

def addQemuNs(domXML):
    domain = domXML.getElementsByTagName('domain')[0]
    domain.setAttribute('xmlns:qemu',
                        'http://libvirt.org/schemas/domain/qemu/1.0')


def injectQemuCmdLine(domXML, qc):
    domain = domXML.getElementsByTagName('domain')[0]
    qctag = domXML.createElement('qemu:commandline')

    for cmd in qc:
        qatag = domXML.createElement('qemu:arg')
        qatag.setAttribute('value', cmd)

        qctag.appendChild(qatag)

    domain.appendChild(qctag)


try:
    domxml = hooking.read_domxml()
    td_qc = json.loads(TD_QC)
    try:
        termidesk_enable = json.loads(domxml.getElementsByTagName("ovirt-vm:termideskCompatible")[0].firstChild.nodeValue.lower())
    except:
        termidesk_enable = False
    if termidesk_enable:
        addQemuNs(domxml)
        injectQemuCmdLine(domxml, td_qc)
        hooking.write_domxml(domxml)
except:
    sys.stderr.write('termidesk: [unexpected error]: %s\n'
                     % traceback.format_exc())
    sys.stderr.write(domxml.toxml())
    sys.exit(2)
