#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# agent output
# <<<win_reg_uninstall:sep(124)>>>
# ...


def inv_win_reg_uninstall(info):
    parsed_packages = []
    for line in info:
        if len(line) == 7:
            display_name, publisher, path, pacname, version, estimated_size, date = line
            language = ""
        elif len(line) == 8:
            display_name, publisher, path, pacname, version, estimated_size, date, language = line
        else:
            continue

        install_date = None
        if re.match(r"^20\d{6}", date):
            # Dates look like '20160930', but we saw also dates like '20132804'
            # which have transposed month and day fields.
            try:
                install_date = int(time.mktime(time.strptime(date, "%Y%m%d")))
            except ValueError:
                try:
                    install_date = int(time.mktime(time.strptime(date, "%Y%d%m")))
                except ValueError:
                    pass

        size = saveint(estimated_size)
        if size == 0:
            size = None
        if pacname.startswith("{"):
            pacname = display_name
        if pacname == "":
            continue

        entry = {
            "name": pacname,
            "version": version,
            "vendor": publisher,
            "summary": display_name,
            "install_date": install_date,
            "size": size,
            "path": path,
            "language": language,
            "package_type": "registry",
        }
        parsed_packages.append(entry)

    paclist = inv_tree_list("software.packages:")
    paclist.extend(sorted(parsed_packages, key=lambda r: r.get('name')))


inv_info['win_reg_uninstall'] = {
    "inv_function": inv_win_reg_uninstall,
}
