#!/usr/bin/python
from argparse import ArgumentParser

import dmidecode
import hashlib


# Generate a machine_id based off dmidecode fields
def generate_machine_id():
    dmixml = dmidecode.dmidecodeXML()

    # Fetch all DMI data into a libxml2.xmlDoc object
    dmixml.SetResultType(dmidecode.DMIXML_DOC)
    xmldoc = dmixml.QuerySection('all')

    # Do some XPath queries on the XML document
    dmixp = xmldoc.xpathNewContext()

    # What to look for - XPath expressions
    keys = ['/dmidecode/SystemInfo/Manufacturer',
            '/dmidecode/SystemInfo/ProductName',
            '/dmidecode/SystemInfo/SerialNumber',
            '/dmidecode/SystemInfo/SystemUUID']

    # Create a sha256 of ^ for machine_id
    machine_id = hashlib.sha256()

    # Run xpath expressions
    for k in keys:
        data = dmixp.xpathEval(k)
        for d in data:
            # Update the hash as we find the fields we are looking for
            machine_id.update(d.get_content())

    del dmixp
    del xmldoc
    # Create sha256 digest
    return machine_id.hexdigest()


if __name__ == "__main__":
    CMDARGS = ArgumentParser(description = "Generate a machine_id based off dmidecode fields")
    CMDARGS.add_argument('-o', '--output', type=str, help='Output file')

    OPTIONS = CMDARGS.parse_args()
    ARGS = vars(OPTIONS)

    machineid =  generate_machine_id()

    if ARGS['output']:
        try:
            with open(ARGS['output'], 'w') as outfile:
                outfile.write(machineid)
        except IOError as ex:
            print ex
    else:
        print machineid
