# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4; coding:utf-8 -*-
#
# Copyright 2002 Ben Escoto
# Copyright 2007 Kenneth Loafman
#
# This file is part of duplicity.
#
# Duplicity is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# Duplicity is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with duplicity; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

"""
Miscellaneous utilities.
"""

import atexit
import csv
import errno
import json
import multiprocessing
import os
import socket
import sys
import traceback
from io import StringIO

import fasteners

from duplicity import config
from duplicity import dup_tarfile
from duplicity import errors
from duplicity import log


def exception_traceback(limit=50):
    """
    Return a string representation of the currently active/raised exception.

    The output format matches the typical Python traceback format.

    :param int limit: The maximum number of traceback levels to include.
    :returns: A string containing the formatted traceback.
    :rtype: str
    """
    type, value, tb = sys.exc_info()  # pylint: disable=redefined-builtin

    lines = traceback.format_tb(tb, limit)
    lines.extend(traceback.format_exception_only(type, value))

    msg = "Traceback (innermost last):\n"
    msg = f"{msg}{str.join('', lines[:-1]):20} {lines[-1]}"

    return msg


def escape(string):
    """
    Convert a filename to a format suitable for logging.

    The filename is quoted and escaped using UTF-8.

    :param bytes or str string: The filename to escape.
    :returns: The escaped filename string.
    :rtype: str
    """
    string = os.fsdecode(string).encode("unicode-escape", "replace")
    return "'%s'" % string.decode("utf8", "replace").replace("'", "\\x27")


def uindex(index):
    """
    Convert a path index to a string for printing.

    :param tuple index: The path index (a tuple of path parts).
    :returns: The path string.
    :rtype: str
    """
    if index:
        return os.path.join(*list(map(os.fsdecode, index)))
    else:
        return "."


def uexc(e):
    """
    Return the exception message as a Unicode string.

    Handles decoding of byte-string arguments using the filesystem encoding.

    :param Exception e: The exception object.
    :returns: The exception message.
    :rtype: str
    """
    # Exceptions in duplicity often have path names in them, which if they are
    # non-ascii will cause a UnicodeDecodeError when implicitly decoding to
    # unicode.  So we decode manually, using the filesystem encoding.
    # 99.99% of the time, this will be a fine encoding to use.
    if e and e.args:
        # Find arg that is a string
        for m in e.args:
            if isinstance(m, str):
                # Already unicode
                return m
            elif isinstance(m, bytes):
                # Encoded, likely in filesystem encoding
                return os.fsdecode(m)
        # If the function did not return yet, we did not
        # succeed in finding a string; return the whole message.
        return str(e)
    else:
        return ""


def maybe_ignore_errors(fn):
    """
    Execute ``fn``, optionally ignoring errors.

    If the global configuration setting ``ignore_errors`` is set to True,
    catch errors and log them but continue execution.

    :param callable fn: The callable to execute.
    :returns: The result of ``fn()``, or None if it failed and ``ignore_errors`` is true.
    """
    try:
        return fn()
    except Exception as e:
        if config.ignore_errors:
            log.Warn(_("IGNORED_ERROR: WARNING: ignoring error as requested: %s: %s") % (e.__class__.__name__, uexc(e)))
            return None
        else:
            raise


class BlackHoleList(list):
    """
    A list that discards everything appended to it.
    """

    def append(self, x):
        """
        Discard the given element.
        """
        pass


class FakeTarFile(object):
    """
    A fake TarFile object that does nothing.
    """

    debug = 0

    def __iter__(self):
        """
        Return an empty iterator.
        """
        return iter([])

    def close(self):
        """
        Do nothing on close.
        """
        pass


def make_tarfile(mode, fp):
    """
    Create a TarFile object with the given mode and file pointer.

    :param str mode: The mode to open the tarfile in.
    :param fp: The file pointer.
    :returns: A TarFile object or a FakeTarFile if it is empty.
    """
    # We often use 'empty' tarfiles for signatures that haven't been filled out
    # yet.  So we want to ignore ReadError exceptions, which are used to signal
    # this.
    try:
        tf = dup_tarfile.TarFile("arbitrary", mode, fp)
        # Now we cause TarFile to not cache TarInfo objects.  It would end up
        # consuming a lot of memory over the lifetime of our long-lasting
        # signature files otherwise.
        tf.members = BlackHoleList()
        return tf
    except dup_tarfile.ReadError:
        return FakeTarFile()


def get_tarinfo_name(ti):
    """
    Return the name of a TarInfo object, ensuring it ends with / if it is a directory.
    """
    # Python versions before 2.6 ensure that directories end with /, but 2.6
    # and later ensure they they *don't* have /.  ::shrug::  Internally, we
    # continue to use pre-2.6 method.
    if ti.isdir() and not ti.name.endswith(r"/"):
        return f"{ti.name}/"
    else:
        return ti.name


def ignore_missing(fn, filename):
    """
    Execute ``fn`` on ``filename``, ignoring ``ENOENT`` errors.

    :param callable fn: The function to execute.
    :param str filename: The filename to pass to the function.
    :raises OSError: If an error other than ``ENOENT`` occurs.
    """
    try:
        fn(filename)
    except OSError as ex:
        if ex.errno == errno.ENOENT:
            pass
        else:
            raise


def acquire_lockfile():
    """
    Acquire the lockfile if it doesn't exist.
    """
    config.lockpath = os.path.join(config.archive_dir_path.name, b"lockfile")
    config.lockfile = fasteners.process_lock.InterProcessLock(config.lockpath)
    log.Log(
        _("Acquiring lockfile %s") % os.fsdecode(config.lockpath),
        log.DEBUG,
    )
    if not config.lockfile.acquire(blocking=False):
        raise errors.FatalError(
            f"Another duplicity instance is already running with this archive directory\n"
            f"If this is not the case, remove {config.lockpath}'.",
            log.ErrorCode.user_error,
        )


@atexit.register
def release_lockfile():
    """
    Release the lockfile.  Don't do anything if it doesn't exist.
    """
    if config.lockfile is not None:
        try:
            config.lockfile.release()
        except Exception as e:
            log.Error(f"Could not release lockfile: {str(e)}")
            pass
        try:
            os.unlink(config.lockpath)
        except Exception as e:
            log.Error(f"Could not delete lockfile: {str(e)}")
            pass
        config.lockfile = None
        config.lockpath = ""


def copyfileobj(infp, outfp, byte_count=-1):
    """
    Copy byte_count bytes from infp to outfp, or all if byte_count < 0

    Returns the number of bytes actually written (may be less than
    byte_count if find eof.  Does not close either fileobj.

    """
    blocksize = 64 * 1024
    bytes_written = 0
    if byte_count < 0:
        while True:
            buf = infp.read(blocksize)
            if not buf:
                break
            bytes_written += len(buf)
            outfp.write(buf)
    else:
        while bytes_written + blocksize <= byte_count:
            buf = infp.read(blocksize)
            if not buf:
                break
            bytes_written += len(buf)
            outfp.write(buf)
        buf = infp.read(byte_count - bytes_written)
        bytes_written += len(buf)
        outfp.write(buf)
    return bytes_written


def which(program):
    """
    Return the absolute path for the given program name.

    :param str program: The name of the program to find.
    :returns: The absolute path to the program, or None if not found.
    :rtype: str or None
    """

    def is_exe(fpath):
        return os.path.isfile(fpath) and os.path.isabs(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.getenv("PATH").split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.abspath(os.path.join(path, program))
            if is_exe(exe_file):
                return exe_file

    return None


def start_debugger():
    """
    Start the debugger if requested by the environment.
    """
    import socket
    import errno

    def is_port_in_use(host: str, port: int) -> bool:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            try:
                # Bind to host on the specified port
                s.bind((host, port))
                return False  # Port is free
            except socket.error as e:
                if e.errno == errno.EADDRINUSE:
                    return True  # Port is already in use
                else:
                    # Something else went wrong
                    raise e

    def fix_path():
        """
        in a dev environment the path is screwed so fix it.
        """
        base = sys.path.pop(0)
        base = base.split(os.path.sep)[:-1]
        base = os.path.sep.join(base)
        sys.path.insert(0, base)

    if os.environ.get("PYDEVD", None) == "vscode":
        try:
            import debugpy  # pylint: disable=import-error
        except ImportError:
            raise errors.FatalError(
                "Module debugpy must be available for debugging.\n"
                "Don't set 'PYDEVD=vscode'\n"
                "to avoid starting debugpy as debugger."
            )
        host = "127.0.0.1"
        pool_nr = 0
        if "multiprocessing" in sys.modules:
            try:
                pool_nr = multiprocessing.current_process()._identity[0]
                print(f"Debugger for Pool Member: {pool_nr}")
            except IndexError:
                print("Debugger not in pool process.")
        port = 5678 + pool_nr

        while is_port_in_use(host, port):
            port += 1
        print(f"Debugger start on port {port}")
        debugpy.listen(port)
        print(f"Waiting for debugger attach on port: {port}")
        debugpy.wait_for_client()
        fix_path()

    elif config.pydevd or os.environ.get("PYDEVD", None):
        try:
            import debugpy  # pylint: disable=import-error
        except ImportError:
            raise errors.FatalError(
                "Module debugpy must be available for debugging.\n"
                "Remove '--pydevd' from command line and unset 'PYDEVD'\n"
                "from the environment to avoid starting the debugger."
            )

        debug_host = "127.0.0.1"
        debug_port = 5678

        # ignition
        print(f"Debugger start on {debug_host}:{debug_port}", file=sys.stderr)
        debugpy.listen([debug_host, debug_port])
        print(f"Waiting for debugger attach on port: {debug_port}", file=sys.stderr)
        debugpy.wait_for_client()
        fix_path()


def merge_dicts(*dict_args):
    """
    Merge multiple dictionaries into a new one.

    Shallow copies each dictionary. Precedence is given to key-value pairs
    in later dictionaries.

    :param dict dict_args: The dictionaries to merge.
    :returns: A new merged dictionary.
    :rtype: dict
    """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result


def csv_args_to_dict(arg):
    """
    Given the string arg in single line csv format, split into pairs (key, val)
    and produce a dictionary from those key:val pairs.
    """
    mydict = {}
    with StringIO(arg) as infile:
        rows = csv.reader(infile)
        for row in rows:
            for i in range(0, len(row), 2):
                mydict[row[i]] = row[i + 1]
    return mydict


class BytesEncoder(json.JSONEncoder):
    """
    JSON doesn't allow byte type values. Converting them to Unicode strings
    """

    def default(self, obj):
        """
        Handle byte types by converting them to Unicode strings.
        """
        if isinstance(obj, bytes):
            return obj.decode()
        return json.JSONEncoder.default(self, obj)
