#!/usr/bin/env python3


import sys
import os


def getValueFromFile(file, index=0):
    if os.path.exists(file):
        with open(file) as f:
            splittedline = f.readline().split()
            if (0 <= index) and (index < len(splittedline)):
                return splittedline[index]
            else:
                return None
    else:
        return None


def getWindowsRelease():
    # Import the needed APIs
    try:
        import win32api
        from win32api import RegQueryValueEx, RegOpenKeyEx, RegCloseKey, GetVersionEx
        from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT
    except ImportError:
        return platform.win32_ver()[0]

    # Initialize default result
    result = None

    # Find out the registry key and some general version infos
    maj, min, buildno, plat, csd = GetVersionEx()

    regkey = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
    keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
    productName = platform._win32_getvalue(keyCurVer, "ProductName", ("", 1))[0]
    # Close key
    RegCloseKey(keyCurVer)

    if (plat == VER_PLATFORM_WIN32_NT) and (maj == 5) and (min == 2):
        # Need to check window server 2003 or windows XP
        if "XP" in productName:
            result = "XP"

    elif (plat == VER_PLATFORM_WIN32_NT) and (maj == 6):
        # Need to check window Vista or windows 7
        if "7" in productName:
            result = "7"

        else:
            result = "Vista"

    if result is None:
        result = platform.win32_ver()[0]

    return result


if (
    (sys.version_info[0] < 2) or (sys.version_info[0] == 2 and sys.version_info[1] < 3)
) and sys.platform.startswith("irix"):
    identification = "Irix"
    systemplatform = identification.lower()
    shortname = identification
else:
    import platform
    import string

    systemtype = platform.system()
    if systemtype == "Darwin":
        system = "MacOS"
        systemplatform = system.lower()
        release = ".".join(platform.mac_ver()[0].split(".")[:2])
        if platform.architecture()[0] == "32bit":
            arch = "i686"
        else:
            arch = "x86_64"
    elif systemtype == "Windows":
        system = systemtype
        systemplatform = system.lower()
        release = getWindowsRelease()

        if platform.architecture()[0] == "32bit":
            arch = "i686"
        else:
            arch = "x86_64"
    elif systemtype == "SunOS":
        sysfile = "/etc/release"
        system = getValueFromFile(sysfile)
        release = getValueFromFile(sysfile, 1)
        systemplatform = system.lower()
        arch = platform.machine()
    else:
        # system = platform.dist()[0]
        # don't rely on ultra-buggy python platform.dist()[0]
        # which just returns a random system
        system = systemtype  # default is just 'Linux'
        release = None
        arch = platform.machine()
        systemplatform = system.lower()
        # Check for Ubuntu
        if os.path.exists("/etc/lsb-release"):
            with open("/etc/lsb-release") as f:
                if f.readline() == "DISTRIB_ID=Ubuntu\n":
                    system = "Ubuntu"
                    release = f.readline().split("=")[1][:-1]
        if system == systemtype:
            for x in ("system", "fedora", "redhat", "mandriva", "mandrake"):
                # overcome bug in python
                sysfile = "/etc/" + x + "-release"
                result = getValueFromFile(sysfile)
                if result != None:
                    system = result
                    if system == "CentOS":
                        # fix a bug in some CentOS 5 distribs
                        # can really not rely on platform.dist() on CentOS...
                        release = getValueFromFile(sysfile, 2)
                    break
        system = system[0].upper() + system[1:]
        if release is None:
            if hasattr(platform, "dist"):
                release = platform.dist()[1]
            else:
                import distro  # needs external package "distro"

                release = distro.linux_distribution()[1]

    identification = system + "-" + release + "-" + arch
    shortname = system + "-" + release

if __name__ == "__main__":
    if len(sys.argv) > 1:
        if sys.argv[1] in ("-p", "--platform"):
            print(systemplatform)
        elif sys.argv[1] in ("-s", "--shortname"):
            print(shortname)
        else:
            print(" Get system identification information ")
            print(
                "       -p or --platform option gives a general information about the platform (linux, windows, irix, macos, solaris)"
            )
            print(
                "       -s or --shortname option gives a system shortname without architecture"
            )
            print("       -h or --help option display this help")
    else:
        print(identification)
