# -*- coding: utf-8 -*-

# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import shutil
import subprocess
import shlex


# Hardened PATH baseline used to resolve bare command basenames (e.g. "patch",
# "userdel", "systemctl"). The callers of exec_command run from RPM scriptlets
# and panel hooks as root; relying on the inherited PATH allows a misconfigured
# or tampered PATH (e.g. /root/.bashrc, sudo PATH preservation, manual admin
# invocation) to shadow system binaries. Pinning a known-good PATH closes that
# defense-in-depth gap.
_SAFE_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"


def _resolve_argv0(argv0):
    """
    Resolve argv[0] to an absolute path.

    If argv0 already contains a path separator, it is returned unchanged
    (the caller has explicitly pinned the binary). Otherwise it is resolved
    via shutil.which() against the hardened _SAFE_PATH so PATH-controlled
    shadowing through the caller's environment cannot influence the result.

    Raises FileNotFoundError if the bare name cannot be located.
    """
    if os.sep in argv0:
        return argv0
    resolved = shutil.which(argv0, path=_SAFE_PATH)
    if resolved is None:
        raise FileNotFoundError(
            "Executable '{}' not found in sanitized PATH".format(argv0))
    return resolved


def _sanitize_env(env):
    """
    Return an env mapping safe to pass to subprocess.

    The child must never inherit a PATH that the caller could have been
    tricked into setting. When env is None, build a minimal env from a
    handful of allow-listed variables. When env is provided, overwrite its
    PATH with the hardened baseline.
    """
    if env is None:
        sanitized = {"PATH": _SAFE_PATH}
        for key in ("LANG", "LC_ALL", "HOME", "USER", "LOGNAME", "TERM"):
            value = os.environ.get(key)
            if value is not None:
                sanitized[key] = value
        return sanitized
    sanitized = dict(env)
    sanitized["PATH"] = _SAFE_PATH
    return sanitized


def parse_command(command):
    """
    Parses a command string into a list of arguments.
    """
    if isinstance(command, str):
        if command.strip() == "":
            return []
        return shlex.split(command)
    elif isinstance(command, list):
        return command
    else:
        return []

def exec_command(command, env=None):
    """
    Execute command
    """
    result = []
    try:
        args = parse_command(command)
        if not args:
            raise ValueError(f"The provided command is not valid: {command}")
        args = [_resolve_argv0(args[0])] + list(args[1:])
        safe_env = _sanitize_env(env)
        p = subprocess.Popen(args, stdout=subprocess.PIPE, env=safe_env, text=True)
        while 1:
            output = p.stdout.readline()
            if not output:
                break
            if output.strip() != "":
                result.append(output.strip())
    except Exception as inst:
        print("Call process error:", str(inst))
    return result


def exec_command_check(command, env=None):
    """
    Execute command and check output
    """
    try:
        args = parse_command(command)
        if not args:
            raise ValueError(f"The provided command is not valid: {command}")
        args = [_resolve_argv0(args[0])] + list(args[1:])
        safe_env = _sanitize_env(env)
        p = subprocess.Popen(args, stdout=subprocess.PIPE, env=safe_env, text=True)
        (res_in_json, err) = p.communicate()
        if (p.returncode != 0):
            return False
        return True
    except Exception as inst:
        print("Call process error(" + command + "): " + str(inst))
    return False
