# -*- encoding=utf-8 -*-
"""
# **********************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# The license is the Mulan PSL v2.
# You can use this according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# **********************************************************************************
"""


import argparse
import re
import sys
import os
import xml.etree.ElementTree as ET

import logging


def read_metadata_file(metadata_file):
    tree = ET.parse(metadata_file)
    root = tree.getroot()
    return root


def get_patch_list(hotpatch):
    patch_list = []
    version = 0
    release = 0
    for child in hotpatch:
        patch_list = []
        version = child.attrib["version"]
        release = child.attrib["release"]
        patch = child.findall('patch')
        for patch_name in patch:
            patch_list.append(patch_name.text)
    return version, release, patch_list


def verifying_field(version, release):
    hotpatch_dict = {}
    issue_id_list = []
    reference_href_list = []
    root = read_metadata_file(args.input)
    hotpatchs = root.iter('hotpatch')
    for child in hotpatchs:
        issue_id_list = []
        reference_href_list = []
        if child.attrib["version"] == version and child.attrib["release"] == release:
            cve_type = child.attrib["type"]
            issue_list = child.findall('issue')
            hotpatch_dict["patch_name"] = "ACC"
            if cve_type not in ["cve", "bugfix", "feature"]:
                raise "fix type:{} not in [cve/bugfix/feature]".format(cve_type)
            for issue in issue_list:
                issue_id = issue.attrib["id"]
                issue_id_list.append(issue_id)
                reference_href = issue.attrib["issue_href"]
                reference_href_list.append(reference_href)
            if args.mode == "SGL":
                name = child.attrib["name"]
                hotpatch_dict["patch_name"] = name
                ver_name = "SGL-%s" % ("-".join(issue_id_list))
                if name != ver_name:
                    raise "hotpatch name is not match issue id, name: {}, issue id: {}" % (name, ver_name)
            src_url = child.find('SRC_RPM').text
            x86_debug = child.find('Debug_RPM_X86_64').text
            aarch64_debug = child.find('Debug_RPM_Aarch64').text
            hotpatch_issue = child.find('hotpatch_issue_link').text
            hotpatch_dict["cve_type"] = cve_type
            hotpatch_dict["hotpatch_issue"] = hotpatch_issue
    hotpatch_dict["issue_id"] = issue_id_list
    hotpatch_dict["reference_href"] = reference_href_list

    return hotpatch_dict


def create_update_info():
    date_pattern = r"\d{4}[-/]\d{2}[-/]\d{2}"
    type_dict = {
        "cve": "security",
        "bugfix": "bugfix",
        "feature": "enhancement"
    }

    root = read_metadata_file(args.input)
    hotpatch = root.iter('hotpatch')

    version, release, patch_list = get_patch_list(hotpatch)
    hotpatch_dict = verifying_field(version, release)

    hotpatch_issue = hotpatch_dict.get("hotpatch_issue")

    with os.fdopen(os.open(args.output, os.O_RDWR | os.O_CREAT, 0o644), "w") as file:
        file.write("patch: " + ",".join(patch_list) + "\n")
        file.write("cve_type: %s\n" % type_dict.get(hotpatch_dict.get("cve_type"), ""))
        file.write("issue_id: %s\n" % ",".join(hotpatch_dict.get("issue_id")))
        file.write("reference-type: %s\n" % hotpatch_dict.get("cve_type"))
        file.write("reference-id: %s\n" % " ".join(hotpatch_dict.get("issue_id")))
        file.write("reference-href: %s\n" % " ".join(hotpatch_dict.get("reference_href")))
        file.write("curr_version: %s\n" % version)
        file.write("curr_release: %s\n" % release)
        file.write("mode: %s\n" % args.mode)
        file.write("patch_name: %s\n" % hotpatch_dict.get("patch_name"))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Parsing hotmetadata.xml')
    parser.add_argument("-i", type=str, dest="input", help="input file")
    parser.add_argument("-o", type=str, dest="output", help="output file")
    parser.add_argument("-m", type=str, dest="mode", help="hotpatch mode")

    args = parser.parse_args()
    create_update_info()
