import os
import os.path
import platform
import subprocess
import sys
import six
import hmac
import hashlib
from errno import ENOENT, ENOEXEC
from cloudinit import log as logging
try:
    string_types = (basestring,)
except NameError:
    string_types = (str,)

_SK = '28c5eea3-10aa-4330-a531-782de1774787'

def _to_utf8(text):
    """Encode Unicode to UTF-8, return bytes unchanged.

    Raise TypeError if text is not a bytes string or a Unicode string.

    .. versionadded:: 3.5
    """
    if isinstance(text, six.binary_type):
        return text
    elif isinstance(text, six.text_type):
        return text.encode('utf-8')
    else:
        raise TypeError("bytes or Unicode expected, got %s"
                        % type(text).__name__)


def get_signature(uuid):
    signature = hmac.new(
        _to_utf8(_SK),
        _to_utf8(uuid),
        hashlib.sha256).hexdigest()
    return signature


LOG = logging.getLogger(__name__)
# Path for DMI Data
DMI_SYS_PATH = "/sys/class/dmi/id"

# dmidecode and /sys/class/dmi/id/* use different names for the same value,
# this allows us to refer to them by one canonical name
DMIDECODE_TO_DMI_SYS_MAPPING = {
    'baseboard-asset-tag': 'board_asset_tag',
    'baseboard-manufacturer': 'board_vendor',
    'baseboard-product-name': 'board_name',
    'baseboard-serial-number': 'board_serial',
    'baseboard-version': 'board_version',
    'bios-release-date': 'bios_date',
    'bios-vendor': 'bios_vendor',
    'bios-version': 'bios_version',
    'chassis-asset-tag': 'chassis_asset_tag',
    'chassis-manufacturer': 'chassis_vendor',
    'chassis-serial-number': 'chassis_serial',
    'chassis-version': 'chassis_version',
    'system-manufacturer': 'sys_vendor',
    'system-product-name': 'product_name',
    'system-serial-number': 'product_serial',
    'system-uuid': 'product_uuid',
    'system-version': 'product_version',
}


def _read_dmi_syspath(key):
    """
    Reads dmi data with from /sys/class/dmi/id
    """
    if key not in DMIDECODE_TO_DMI_SYS_MAPPING:
        return None
    mapped_key = DMIDECODE_TO_DMI_SYS_MAPPING[key]
    dmi_key_path = "{0}/{1}".format(DMI_SYS_PATH, mapped_key)
    LOG.debug("querying dmi data %s", dmi_key_path)
    try:
        if not os.path.exists(dmi_key_path):
            LOG.debug("did not find %s", dmi_key_path)
            return None

        key_data = load_file(dmi_key_path, decode=False)
        if not key_data:
            LOG.debug("%s did not return any data", dmi_key_path)
            return None

        # uninitialized dmi values show as all \xff and /sys appends a '\n'.
        # in that event, return a string of '.' in the same length.
        if key_data == b'\xff' * (len(key_data) - 1) + b'\n':
            key_data = b""

        str_data = key_data.decode('utf8').strip()
        LOG.debug("dmi data %s returned %s", dmi_key_path, str_data)
        return str_data

    except Exception:
        logexc(LOG, "failed read of %s", dmi_key_path)
        return None


def _call_dmidecode(key, dmidecode_path):
    """
    Calls out to dmidecode to get the data out. This is mostly for supporting
    OS's without /sys/class/dmi/id support.
    """
    try:
        cmd = [dmidecode_path, "--string", key]
        (result, _err) = subp(cmd)
        LOG.debug("dmidecode returned '%s' for '%s'", result, key)
        result = result.strip()
        if result.replace(".", "") == "":
            return ""
        return result
    except (IOError, OSError) as e:
        LOG.debug('failed dmidecode cmd: %s\n%s', cmd, e)
        return None


def is_x86(uname_arch=None):
    """Return True if platform is x86-based"""
    if uname_arch is None:
        uname_arch = os.uname()[4]
    x86_arch_match = (
        uname_arch == 'x86_64' or
        (uname_arch[0] == 'i' and uname_arch[2:] == '86'))
    return x86_arch_match


def read_dmi_data(key):
    """
    Wrapper for reading DMI data.

    If running in a container return None.  This is because DMI data is
    assumed to be not useful in a container as it does not represent the
    container but rather the host.

    This will do the following (returning the first that produces a
    result):
        1) Use a mapping to translate `key` from dmidecode naming to
           sysfs naming and look in /sys/class/dmi/... for a value.
        2) Use `key` as a sysfs key directly and look in /sys/class/dmi/...
        3) Fall-back to passing `key` to `dmidecode --string`.

    If all of the above fail to find a value, None will be returned.
    """

    #if is_container():
    #    return None

    syspath_value = _read_dmi_syspath(key)
    if syspath_value is not None:
        return syspath_value

    # running dmidecode can be problematic on some arches (LP: #1243287)
    uname_arch = os.uname()[4]
    if not (is_x86(uname_arch) or
            uname_arch == 'aarch64' or
            uname_arch == 'amd64'):
        LOG.debug("dmidata is not supported on %s", uname_arch)
        return None

    dmidecode_path = which('dmidecode')
    if dmidecode_path:
        return _call_dmidecode(key, dmidecode_path)

    LOG.warning("did not find either path %s or dmidecode command",
                DMI_SYS_PATH)
    return None


def load_file(fname, read_cb=None, quiet=False, decode=True):
    LOG.debug("Reading from %s (quiet=%s)", fname, quiet)
    ofh = six.BytesIO()
    try:
        with open(fname, 'rb') as ifh:
            pipe_in_out(ifh, ofh, chunk_cb=read_cb)
    except IOError as e:
        if not quiet:
            raise
        if e.errno != ENOENT:
            raise
    contents = ofh.getvalue()
    LOG.debug("Read %s bytes from %s", len(contents), fname)
    if decode:
        return decode_binary(contents)
    else:
        return contents


def pipe_in_out(in_fh, out_fh, chunk_size=1024, chunk_cb=None):
    bytes_piped = 0
    while True:
        data = in_fh.read(chunk_size)
        if len(data) == 0:
            break
        else:
            out_fh.write(data)
            bytes_piped += len(data)
            if chunk_cb:
                chunk_cb(bytes_piped)
    out_fh.flush()
    return bytes_piped


def decode_binary(blob, encoding='utf-8'):
    # Converts a binary type into a text type using given encoding.
    if isinstance(blob, six.string_types):
        return blob
    return blob.decode(encoding)


def which(program, search=None, target=None):
    target = target_path(target)

    if os.path.sep in program:
        # if program had a '/' in it, then do not search PATH
        # 'which' does consider cwd here. (cd / && which bin/ls) = bin/ls
        # so effectively we set cwd to / (or target)
        if is_exe(target_path(target, program)):
            return program

    if search is None:
        paths = [p.strip('"') for p in
                 os.environ.get("PATH", "").split(os.pathsep)]
        if target == "/":
            search = paths
        else:
            search = [p for p in paths if p.startswith("/")]

    # normalize path input
    search = [os.path.abspath(p) for p in search]

    for path in search:
        ppath = os.path.sep.join((path, program))
        if is_exe(target_path(target, ppath)):
            return ppath

    return None


def is_exe(fpath):
    # return boolean indicating if fpath exists and is executable.
    return os.path.isfile(fpath) and os.access(fpath, os.X_OK)


def target_path(target, path=None):
    # return 'path' inside target, accepting target as None
    if target in (None, ""):
        target = "/"
    elif not isinstance(target, string_types):
        raise ValueError("Unexpected input for target: %s" % target)
    else:
        target = os.path.abspath(target)
        # abspath("//") returns "//" specifically for 2 slashes.
        if target.startswith("//"):
            target = target[1:]

    if not path:
        return target

    # os.path.join("/etc", "/foo") returns "/foo". Chomp all leading /.
    while len(path) and path[0] == "/":
        path = path[1:]

    return os.path.join(target, path)


def logexc(log, msg, *args):
    # Setting this here allows this to change
    # levels easily (not always error level)
    # or even desirable to have that much junk
    # coming out to a non-debug stream
    if msg:
        log.warning(msg, *args)
    # Debug gets the full trace.  However, nose has a bug whereby its
    # logcapture plugin doesn't properly handle the case where there is no
    # actual exception.  To avoid tracebacks during the test suite then, we'll
    # do the actual exc_info extraction here, and if there is no exception in
    # flight, we'll just pass in None.
    exc_info = sys.exc_info()
    if exc_info == (None, None, None):
        exc_info = None
    log.debug(msg, exc_info=exc_info, *args)


def subp(args, data=None, rcs=None, env=None, capture=True,
         combine_capture=False, shell=False,
         logstring=False, decode="replace", target=None, update_env=None,
         status_cb=None):
    """Run a subprocess.

    :param args: command to run in a list. [cmd, arg1, arg2...]
    :param data: input to the command, made available on its stdin.
    :param rcs:
        a list of allowed return codes.  If subprocess exits with a value not
        in this list, a ProcessExecutionError will be raised.  By default,
        data is returned as a string.  See 'decode' parameter.
    :param env: a dictionary for the command's environment.
    :param capture:
        boolean indicating if output should be captured.  If True, then stderr
        and stdout will be returned.  If False, they will not be redirected.
    :param combine_capture:
        boolean indicating if stderr should be redirected to stdout. When True,
        interleaved stderr and stdout will be returned as the first element of
        a tuple, the second will be empty string or bytes (per decode).
        if combine_capture is True, then output is captured independent of
        the value of capture.
    :param shell: boolean indicating if this should be run with a shell.
    :param logstring:
        the command will be logged to DEBUG.  If it contains info that should
        not be logged, then logstring will be logged instead.
    :param decode:
        if False, no decoding will be done and returned stdout and stderr will
        be bytes.  Other allowed values are 'strict', 'ignore', and 'replace'.
        These values are passed through to bytes().decode() as the 'errors'
        parameter.  There is no support for decoding to other than utf-8.
    :param target:
        not supported, kwarg present only to make function signature similar
        to curtin's subp.
    :param update_env:
        update the enviornment for this command with this dictionary.
        this will not affect the current processes os.environ.
    :param status_cb:
        call this fuction with a single string argument before starting
        and after finishing.

    :return
        if not capturing, return is (None, None)
        if capturing, stdout and stderr are returned.
            if decode:
                entries in tuple will be python2 unicode or python3 string
            if not decode:
                entries in tuple will be python2 string or python3 bytes
    """

    # not supported in cloud-init (yet), for now kept in the call signature
    # to ease maintaining code shared between cloud-init and curtin
    if target is not None:
        raise ValueError("target arg not supported by cloud-init")

    if rcs is None:
        rcs = [0]

    devnull_fp = None

    if update_env:
        if env is None:
            env = os.environ
        env = env.copy()
        env.update(update_env)

    if target_path(target) != "/":
        args = ['chroot', target] + list(args)

    if status_cb:
        command = ' '.join(args) if isinstance(args, list) else args
        status_cb('Begin run command: {command}\n'.format(command=command))
    if not logstring:
        LOG.debug(("Running command %s with allowed return codes %s"
                   " (shell=%s, capture=%s)"),
                  args, rcs, shell, 'combine' if combine_capture else capture)
    else:
        LOG.debug(("Running hidden command to protect sensitive "
                   "input/output logstring: %s"), logstring)

    stdin = None
    stdout = None
    stderr = None
    if capture:
        stdout = subprocess.PIPE
        stderr = subprocess.PIPE
    if combine_capture:
        stdout = subprocess.PIPE
        stderr = subprocess.STDOUT
    if data is None:
        # using devnull assures any reads get null, rather
        # than possibly waiting on input.
        devnull_fp = open(os.devnull)
        stdin = devnull_fp
    else:
        stdin = subprocess.PIPE
        if not isinstance(data, bytes):
            data = data.encode()

    # Popen converts entries in the arguments array from non-bytes to bytes.
    # When locale is unset it may use ascii for that encoding which can
    # cause UnicodeDecodeErrors. (LP: #1751051)
    if isinstance(args, six.binary_type):
        bytes_args = args
    elif isinstance(args, six.string_types):
        bytes_args = args.encode("utf-8")
    else:
        bytes_args = [
            x if isinstance(x, six.binary_type) else x.encode("utf-8")
            for x in args]
    try:
        sp = subprocess.Popen(bytes_args, stdout=stdout,
                              stderr=stderr, stdin=stdin,
                              env=env, shell=shell)
        (out, err) = sp.communicate(data)
    except OSError as e:
        if status_cb:
            status_cb('ERROR: End run command: invalid command provided\n')
        raise ProcessExecutionError(
            cmd=args, reason=e, errno=e.errno,
            stdout="-" if decode else b"-",
            stderr="-" if decode else b"-")
    finally:
        if devnull_fp:
            devnull_fp.close()

    # Just ensure blank instead of none.
    if capture or combine_capture:
        if not out:
            out = b''
        if not err:
            err = b''
    if decode:
        def ldecode(data, m='utf-8'):
            if not isinstance(data, bytes):
                return data
            return data.decode(m, decode)

        out = ldecode(out)
        err = ldecode(err)

    rc = sp.returncode
    if rc not in rcs:
        if status_cb:
            status_cb(
                'ERROR: End run command: exit({code})\n'.format(code=rc))
        raise ProcessExecutionError(stdout=out, stderr=err,
                                    exit_code=rc,
                                    cmd=args)
    if status_cb:
        status_cb('End run command: exit({code})\n'.format(code=rc))
    return (out, err)

class ProcessExecutionError(IOError):

    MESSAGE_TMPL = ('%(description)s\n'
                    'Command: %(cmd)s\n'
                    'Exit code: %(exit_code)s\n'
                    'Reason: %(reason)s\n'
                    'Stdout: %(stdout)s\n'
                    'Stderr: %(stderr)s')
    empty_attr = '-'

    def __init__(self, stdout=None, stderr=None,
                 exit_code=None, cmd=None,
                 description=None, reason=None,
                 errno=None):
        if not cmd:
            self.cmd = self.empty_attr
        else:
            self.cmd = cmd

        if not description:
            if not exit_code and errno == ENOEXEC:
                self.description = 'Exec format error. Missing #! in script?'
            else:
                self.description = 'Unexpected error while running command.'
        else:
            self.description = description

        if not isinstance(exit_code, six.integer_types):
            self.exit_code = self.empty_attr
        else:
            self.exit_code = exit_code

        if not stderr:
            if stderr is None:
                self.stderr = self.empty_attr
            else:
                self.stderr = stderr
        else:
            self.stderr = self._indent_text(stderr)

        if not stdout:
            if stdout is None:
                self.stdout = self.empty_attr
            else:
                self.stdout = stdout
        else:
            self.stdout = self._indent_text(stdout)

        if reason:
            self.reason = reason
        else:
            self.reason = self.empty_attr

        self.errno = errno
        message = self.MESSAGE_TMPL % {
            'description': self._ensure_string(self.description),
            'cmd': self._ensure_string(self.cmd),
            'exit_code': self._ensure_string(self.exit_code),
            'stdout': self._ensure_string(self.stdout),
            'stderr': self._ensure_string(self.stderr),
            'reason': self._ensure_string(self.reason),
        }
        IOError.__init__(self, message)

    def _ensure_string(self, text):
        """
        if data is bytes object, decode
        """
        return text.decode() if isinstance(text, six.binary_type) else text

    def _indent_text(self, text, indent_level=8):
        """
        indent text on all but the first line, allowing for easy to read output
        """
        cr = '\n'
        indent = ' ' * indent_level
        # if input is bytes, return bytes
        if isinstance(text, six.binary_type):
            cr = cr.encode()
            indent = indent.encode()
        # remove any newlines at end of text first to prevent unneeded blank
        # line in output
        return text.rstrip(cr).replace(cr, cr + indent)
