# Copyright 2014-2021 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

import logging
import os
from collections import OrderedDict
from warnings import warn

import portage
from portage.output import create_color_func
from portage.util import _recursive_file_list, writemsg_level

bad = create_color_func("BAD")
warn = create_color_func("WARN")


def get_hooks_from_dir(rel_directory, prefix="/"):
    directory = os.path.join(prefix, portage.USER_CONFIG_PATH, rel_directory)

    hooks = OrderedDict()
    for filepath in _recursive_file_list(directory):
        name = filepath.split(directory)[1].lstrip(os.sep)
        if os.access(filepath, os.X_OK):
            hooks[filepath] = name
        else:
            writemsg_level(
                f" {warn('*')} {directory} hook: '{name}' is not executable\n",
                level=logging.WARNING,
                noiselevel=2,
            )

    return hooks


def perform_hooks(rel_directory, *argv, prefix="/"):
    for filepath, name in get_hooks_from_dir(rel_directory, prefix).items():
        hook_command = filepath + " " + " ".join(map(str, argv))
        retval = portage.process.spawn(hook_command)

        if retval != os.EX_OK:
            writemsg_level(
                f" {bad('*')} Spawn failed for: {name}, {filepath}\n",
                level=logging.ERROR,
                noiselevel=-1,
            )
