#!/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.

# Example output
# <<<win_wmi_software:sep(124)>>>
# 64 Bit HP CIO Components Installer|Hewlett-Packard|15.2.1
# Adobe Flash Player 12 ActiveX|Adobe Systems Incorporated|12.0.0.70
# Microsoft Visio 2010 Interactive Guide DEU|Microsoft|1.2.1
# Microsoft Outlook 2010 Interactive Guide DEU|Microsoft|1.2.1
# VMware vSphere Client 4.1|VMware, Inc.|4.1.0.17435
# Microsoft Office Professional Plus 2010|Microsoft Corporation|14.0.7015.1000


def inv_win_wmi_software(info):
    parsed_packages = []
    for line in info:
        if len(line) < 3:
            continue

        pacname, vendor, version = line[:3]
        dat = line[3]

        install_date = None
        if len(dat) == 8 and re.match("^20", dat):
            install_date = int(time.mktime(time.strptime(dat, "%Y%m%d")))

        # contains language as well
        if len(line) == 5:
            language = line[4]
        else:
            language = ""

        entry = {
            "name": pacname,
            "version": version,
            "vendor": vendor.replace('\x00', ''),  # Can happen, reason unclear
            "install_date": install_date,
            "language": language,
            "package_type": "wmi",
        }
        parsed_packages.append(entry)

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


inv_info['win_wmi_software'] = {
    "inv_function": inv_win_wmi_software,
}
