#!/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_exefiles:sep(124)>>>
# C:\Program Files\Common Files\Microsoft Shared\MSInfo\msinfo32.exe|378880
# C:\Program Files\Common Files\Microsoft Shared\OFFICE15\CMigrate.exe|6847704
# C:\Program Files\Common Files\Microsoft Shared\OFFICE15\MSOXMLED.EXE|217200
# C:\Program Files\Common Files\Microsoft Shared\OfficeSoftwareProtectionPlatform\OSPPSVC.EXE|5132888


def inv_win_exefiles(info):
    parsed_packages = []
    for line in info:
        if len(line) != 6:
            continue  # ignore broken lines containing parse errors
        full_name, write_time, size, description, product_version, product_name = line
        parts = full_name.split('\\')
        # Since 1.2.6p1 the agent always provides a date format of "04/18/2003 18:06:32".
        # Old agent versions provided localized date formats which lead to problems here
        # when none of the implemented parsers matches. We keep the existing parsers for
        # compatibility, all users with yet unhandled formats should update the agent to
        # solve the problems.
        if re.match(r"^\d{2}\.\d{2}\.20\d{2} \d{2}:\d{2}:\d{2}", write_time):
            install_date = int(time.mktime(time.strptime(write_time, "%d.%m.%Y %H:%M:%S")))
        elif re.match(r"^\d{1,2}/\d{1,2}/20\d{2} \d{1,2}:\d{2}:\d{2} (AM|PM)", write_time):
            install_date = int(time.mktime(time.strptime(write_time, "%m/%d/%Y %H:%M:%S %p")))
        elif re.match(r"^\d{1,2}/\d{1,2}/20\d{2} \d{1,2}:\d{2}:\d{2}", write_time):
            # This is the 1.2.6p1 new default date
            install_date = int(time.mktime(time.strptime(write_time, "%m/%d/%Y %H:%M:%S")))
        else:
            install_date = None

        entry = {
            "name": parts[-1],
            "path": "\\".join(parts[:-1]),
            "package_type": "exe",
            "install_date": install_date,
            "size": saveint(size),
            "version": product_version,
            "summary": description,
            "vendor": product_name,
        }
        parsed_packages.append(entry)

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


inv_info['win_exefiles'] = {
    "inv_function": inv_win_exefiles,
}
