#!/usr/bin/env python3

# Written By - Rishabh Das <rishabh5290@gmail.com>
# Modified By - Alexandre Iooss <erdnaxe@crans.org>
#
# This program is a free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the license, or(at your option) any
# later version. See http://www.gnu.org/copyleft/gpl.html for the full text of
# the license.

##############################################################################

DOCUMENTATION = '''
---
module: dmidecode
version_added: "0.1"
short_description: Get dmidecode information for your infrastructure.
description:
    - Get the dmidecode information of your infrastructure.
'''

EXAMPLES = '''
# dmidecode module takes in 'save' as a paramter. If set True,
# this stores the dmidecode JSON output on the target machine.
# This by default is set to False.

# Usage Examples -

- name: Get dmidecode data
  action: dmidecode

'''

import json

from ansible.module_utils.basic import AnsibleModule


def decode_dict(data):
    data_type = type(data)
    if data == None: return ""
    if data_type == bytes: return data.decode()
    if data_type in (str, int, bool): return str(data)
    if data_type == dict: data = data.items()
    return data_type(map(decode_dict, data))

def run_module():
    module = AnsibleModule(
        argument_spec = {},
        supports_check_mode=True,
    )

    try:
        import dmidecode
        dmi_data = decode_dict({
            'bios': dmidecode.bios(),
            'processor': dmidecode.processor(),
            'system': dmidecode.system(),
            'memory': dmidecode.memory(),
            'slot': dmidecode.slot(),
        })
        
    except ImportError:
        dmi_data = {
            'bios': dict(),
            'processor': dict(),
            'system': dict(),
            'memory': dict(),
            'slot': dict(),
        }

    module.exit_json(changed=False, ansible_facts=dmi_data)


def main():
    run_module()


if __name__ == '__main__':
    main()