#%copyright%

import shlex
import subprocess
import sys


def exec_command(command):
    result = []
    try:
        argv = command if isinstance(command, list) else shlex.split(command)
        p = subprocess.Popen(argv, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        while 1:
            output = p.stdout.readline()
            if not output:
                break
            if output.strip() != "":
                result.append(output.decode().strip())
    except Exception as inst:
        # Must go to stderr: callers such as `switch_mod_lsapi --stat` emit
        # machine-readable JSON on stdout, and any text printed here would
        # corrupt it (e.g. break json.loads in cloudlinux-summary).
        print("Call process error: " + str(inst), file=sys.stderr)
    return result


def exec_command_out(command):
    """
    Run command and return its exit status.

    :param command: Command to execute as a list or string
    :return: Exit status of the command process
    """
    argv = command if isinstance(command, list) else shlex.split(command)
    try:
        return subprocess.run(argv, shell=False).returncode
    except (FileNotFoundError, PermissionError):
        return 127


def exec_command_find_substring(command, substring):
    result = exec_command(command)
    for i in result:
        if substring in i:
            return i
    return -1
