# 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 logging
import platforms
import subprocess

DEFAULT_WAIT_TIMEOUT = 30

def shell_run(command, raw_output=True, timeout=0, **kwargs):
    output = ''
    error = ''
    if isinstance(command, str):
        kwargs['shell'] = True
    if platforms.PLATFORM == 'win':
        kwargs['creationflags'] = subprocess.CREATE_NO_WINDOW
    if timeout:
        kwargs['timeout'] = timeout
    try:
        process = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, **kwargs)
    except subprocess.SubprocessError as e:
        error = str(e)
        logging.getLogger().warning(f'Warning from running {command}: {error}')
    except Exception as e:
        error = str(e)
        logging.getLogger().warning(f'Unknown error from {command}: {error}')
    else:
        if getattr(process, 'stdout', None):
            output = process.stdout.strip()
        if not error:
            if process.returncode:
                error = str(process.returncode)
    return output, error
