#!/usr/libexec/platform-python
#
# Copyright (c) 2020-2021 Virtuozzo International GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation;
# either version 2.1 of the License, or (at your option) any
# later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with the product.  If not, see
# <http://www.gnu.org/licenses/>.
#
# Our contact details: Virtuozzo International GmbH, Vordergasse 59, 8200
# Schaffhausen, Switzerland.
#

import os
import sys
import subprocess
from xml.dom import minidom

def get_mount_info():
    try:
        p = subprocess.Popen(['mount'], env=os.environ, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        mountInfo = p.stdout.read()
        return mountInfo.decode('utf-8')
    except:
        return ''

def get_meminfo(path):
    try:
        p = subprocess.Popen(['cat', '/proc/meminfo'], env=os.environ, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        cfg = open(path + '/meminfo.txt', 'w')
        cfg.write(p.stdout.read())
        cfg.close()
        return True
    except:
        return False

def get_network_cfg(path):
    try:
        p = subprocess.Popen(['ip', 'a'], env=os.environ, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        network_cfg = open(path + '/network_cfg.txt', 'w')
        network_cfg.write(p.stdout.read())
        network_cfg.close()
        return True
    except:
        return False

def get_license(path):
    try:
        p = subprocess.Popen(['vzlicview'], env=os.environ, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        allProcesses = open(path + '/vzlicview.txt', 'w')
        allProcesses.write(p.stdout.read())
        allProcesses.close()
        return True
    except:
        return False

def get_storage_license(path):
    if not os.path.isdir("/etc/vstorage/clusters"):
        return False
    clusters = os.listdir("/etc/vstorage/clusters")
    if not clusters:
        return False
    try:
        for cluster_name in clusters:
            p = subprocess.Popen(['vstorage', '-c', cluster_name, 'view-license'], env=os.environ, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            allProcesses = open(path + '/vzlic_storage.txt', 'a')
            allProcesses.write(p.stdout.read())
            allProcesses.close()
        return True
    except:
        return False

def get_product_name():
    try:
        if (os.path.isfile('/etc/virtuozzo-release')):
            productName = open('/etc/virtuozzo-release', 'r').read().replace('\n', '')
        elif (os.path.isfile('/etc/hci-release')):
            productName = open('/etc/hci-release', 'r').read().replace('\n', '')
        else:
            productName = open('/etc/system-release', 'r').read().replace('\n', '')
        return productName
    except:
        return ''

def generate_report_xml(path):
    doc = minidom.Document()
    top = doc.createElement('VirtuozzoProblemReport')
    doc.appendChild(top)
    childType = doc.createElement('Type')
    childTypeText = doc.createTextNode('5')
    childType.appendChild(childTypeText)
    top.appendChild(childType)

    childProductName = doc.createElement('ProductName')
    childProductNameText = doc.createTextNode(get_product_name())
    childProductName.appendChild(childProductNameText)
    top.appendChild(childProductName)

    c = doc.createElement('ReportReason')
    cText = doc.createTextNode("0")
    c.appendChild(cText)
    top.appendChild(c)

    c = doc.createElement('ProblemCode')
    cText = doc.createTextNode("0")
    c.appendChild(cText)
    top.appendChild(c)

    childInstalledSoftware = doc.createElement('InstalledSoftware')
    childInstalledSoftwareText = doc.createCDATASection('InstalledSoftware.txt')
    childInstalledSoftware.appendChild(childInstalledSoftwareText)
    top.appendChild(childInstalledSoftware)

    childMoreHostInfo = doc.createElement('MoreHostInfo')
    childMoreHostInfoText = doc.createCDATASection('MoreHostInfo.xml')
    childMoreHostInfo.appendChild(childMoreHostInfoText)
    top.appendChild(childMoreHostInfo)

    childAllProcesses = doc.createElement('AllProcesses')
    childAllProcessesText = doc.createCDATASection('AllProcesses.txt')
    childAllProcesses.appendChild(childAllProcessesText)
    top.appendChild(childAllProcesses)

    if get_network_cfg(path):
        childNetworkCfg = doc.createElement('NetworkConfiguration')
        childNetworkCfgText = doc.createCDATASection('network_cfg.txt')
        childNetworkCfg.appendChild(childNetworkCfgText)
        top.appendChild(childNetworkCfg)
    if get_meminfo(path):
        childCfg = doc.createElement('MemInfo')
        childCfgText = doc.createCDATASection('meminfo.txt')
        childCfg.appendChild(childCfgText)
        top.appendChild(childCfg)
    if get_license(path):
        childLic = doc.createElement('License')
        childLicText = doc.createCDATASection('vzlicview.txt')
        childLic.appendChild(childLicText)
        top.appendChild(childLic)
    if get_storage_license(path):
        childLicStor = doc.createElement('StorageLicense')
        childLicStorText = doc.createCDATASection('vzlic_storage.txt')
        childLicStor.appendChild(childLicStorText)
        top.appendChild(childLicStor)
    childMountInfo = doc.createElement('MountInfo')
    childMountInfoText = doc.createCDATASection(get_mount_info())
    childMountInfo.appendChild(childMountInfoText)
    top.appendChild(childMountInfo)

    reportXML = open(path + '/Report.xml', 'w')
    reportXML.write(doc.toprettyxml(indent="  "))
    reportXML.close()

if __name__ == "__main__":
    generate_report_xml(sys.argv[1])
