# Copyright 3D Control Systems, Inc. All Rights Reserved 2017-2019.
# Built in San Francisco.

# This software is distributed under a commercial license for personal,
# educational, corporate or any other use.
# The software as a whole or any parts of it is prohibited for distribution or
# use without obtaining a license from 3D Control Systems, Inc.

# All software licenses are subject to the 3DPrinterOS terms of use
# (available at https://www.3dprinteros.com/terms-and-conditions/),
# and privacy policy (available at https://www.3dprinteros.com/privacy-policy/)

import os
import platform
import subprocess


MODEL_NAME_FILE = "/sys/firmware/devicetree/base/model"
UNDERVOLTAGE_FILE = '/sys/class/hwmon/hwmon1/in0_lcrit_alarm'
BACKUP_MODEL_GET_COMMAND = r"dmesg | grep 'Machine model' | sed -r 's/(^.+)(Machine model:\s+)(.+)/\3/g'"
FULL_PLATFORM_LINE = platform.platform().lower()


def get_platform():
    if FULL_PLATFORM_LINE.startswith('linux') and ('arm' in FULL_PLATFORM_LINE or 'aarch64' in FULL_PLATFORM_LINE):
        return 'rpi'
    elif FULL_PLATFORM_LINE.startswith('linux'):
        return 'linux'
    elif FULL_PLATFORM_LINE.startswith('darwin') or FULL_PLATFORM_LINE.startswith('macos'):
        return 'mac'
    elif FULL_PLATFORM_LINE.startswith('windows'):
        return 'win'


def get_arch():
    return platform.machine()


def get_machine_model_name():
    if get_platform() == 'rpi':
        try:
            if os.path.exists(MODEL_NAME_FILE):
                with open(MODEL_NAME_FILE) as f:
                    model_name = f.read()
                    if model_name:
                        return model_name
                    raise ValueError
        except (OSError, TypeError, ValueError):
            try:
                return subprocess.check_output(BACKUP_MODEL_GET_COMMAND, shell=True, text=True).strip()
            except:
                pass
    return ''


PLATFORM = get_platform()
ARCH = get_arch()
MACHINE = get_machine_model_name()

def undervoltage_detected():
    try:
        if os.path.exists(UNDERVOLTAGE_FILE):
            with open(UNDERVOLTAGE_FILE) as f:
                return bool(int(f.read()))
    except (OSError, TypeError, ValueError):
        pass

if __name__ == "__main__":
    print(FULL_PLATFORM_LINE, get_platform())
    uvd = undervoltage_detected()
    if uvd:
        print('Warning! Under-voltage detected')
    elif uvd is False:
        print('No under-voltage detected')
