#!/usr/bin/python3

import subprocess

def scanSystem():
    global serial, model, manufacturer, os
    
    serialfiles = ['/sys/class/dmi/id/product_serial', '/sys/class/dmi/id/chassis_serial', '/sys/class/dmi/id/board_serial']
    serial = findInfo(serialfiles, [], "system serial number")

    modelfiles = ['/sys/class/dmi/id/board_name', '/sys/class/dmi/id/product_name']
    model = findInfo(modelfiles, [], "system model")

    manufacturerfiles = ['/sys/class/dmi/id/board_vendor', '/sys/class/dmi/id/chassis_vendor', '/sys/class/dmi/id/product_vendor']
    manufacturer = findInfo(manufacturerfiles, [], "manufacturer")

    osfiles = ['/etc/issue.net']
    oscmds = ['/bin/bash -c "lsb_release -d | cut -c 14-"',
            '/bin/bash -c "cat /etc/os-release | grep \\"PRETTY_NAME\\" | head -n 1 | cut -c 14- | sed \\"s/\\\\\\"//\\""',
            '/bin/bash -c "cat /etc/issue | head -n 1 | sed \\"s/ \\\\\\\\\\\\n \\\\\\\\\\\\l//\\""']
    os = findInfo(osfiles, oscmds, "operating system")

    print("\nMachine Info:")

    print("\tSerial:       " + serial)
    print("\tModel:        " + model)
    print("\tManufacturer: " + manufacturer)
    print("\tOS:           " + os)
    
    print()

    promptUpload()

def findInfo(filenames, commands, human_name):
    bad_values = ["", "Default string", "Not Present", "None", "Not Specified", "Other", "UNKNOWN", "Unknown", "<OUT OF SPEC>", "0x00000000", "To Be Filled By O.E.M.", "<BAD INDEX>", "NO DIMM", "No Module Installed", "0123456789"]
    items = []
    
    for filename in filenames:
        try:
            with open(filename, 'r') as filefile:
                value = str(filefile.read()).strip()
                if value not in bad_values:
                    items.append(value)
        except:
            pass
    
    for command in commands:
        try:
            stdout = subprocess.check_output(command, shell=True)
            value = stdout.decode().strip()
            if value not in bad_values:
                items.append(value)
        except:
            pass
            
    deduped = list(set(items))
    
    if len(deduped) == 1:
        return deduped[0]
    elif len(deduped) > 1:
        print("\nMultiple values found for the " + human_name + ":")
        value = 1
        for item in deduped:
            print("\t" + str(value) + ": " + item);
            value += 1
        manual_entry = input("Choose an option or type a manual entry: ")
    
        try:
            index = int(manual_entry)
            if index - 1 < len(deduped):
                return deduped[index - 1]
        except ValueError:    
            pass
        
        return manual_entry.strip()
    else:
        manual_entry = input("No value found for the " + human_name + ". Enter one manually: ")
        return manual_entry.strip()
    
def upload(id, serial, model, manufacturer, os):
    print(', '.join([id, serial, model, manufacturer, os]))
    print("Uploading... (NOT IMPLEMENTED)")
    print("Finished!")

def promptUpload():
    q = input("Upload to MachineManager (u for update, r for rescan) (y/N/u/r)? ").lower()
    if q == "y":
        upload("", serial, model, manufacturer, os)
    elif q == "u":
        id = input("Enter machine ID to update: ")
        if len(id.strip()) > 0:
            upload(id.strip(), serial, model, manufacturer, os)
        else:
            print("Invalid machine ID.")
            promptUpload()
    elif q == "n":
        print("Exiting.")
        exit()
    elif q == "r":
        print("Rescanning system...")
        scanSystem()
    else:
        print("Invalid selection.")
        promptUpload()
        
if (__name__ == "__main__"):
    
    print("MachineManager automatic machine uploader script v1.0")
    print("Copyright (c) 2020 Netsyms Technologies")
    
    scanSystem()
