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

import functools
import os
from pathlib import Path

LIBDIR = Path('/usr/share/cagefs')

UNIVERSAL_HOOK_PATH_DNF = Path('/etc/dnf/universal-hooks/multi_pkgs/transaction')
UNIVERSAL_HOOK_PATH_YUM = Path('/etc/yum/universal-hooks/multi_pkgs/posttrans')
UNIVERSAL_HOOK_PATH_APT = Path('/etc/apt/universal-hooks/multi_pkgs/Post-Invoke')

MULTIPHP_UNIVERSAL_HOOK_SCRIPT = 'setup_multiphp_integration'
MULTIPHP_UNIVERSAL_HOOK_NAME = 'setup_multiphp_integration.sh'
PHP_FPM_WITHOUT_LVE_UNIVERSAL_HOOK_SCRIPT = 'fix_fpm_services_in_container'
PHP_FPM_WITHOUT_LVE_UNIVERSAL_HOOK_NAME = 'zzz-cagefs.sh'
PASSENGER_UNIVERSAL_HOOK_NAME = '065-passenger-cagefs'

# '__WILDCARD__php-fpm__WILDCARD__' - for ea-php fpm and naive php-fpm packages
# 'alt-php__WILDCARD__-cli', 'alt-php__WILDCARD__-fpm' - for alt-php fpm packages
# NOTE: alt-php previosly contained fpm services in alt-php*-cli packages,
#       but at some point they were moved to separate alt-php*-fpm packages
PHP_FPM_WILDCARD_DIRS = ['__WILDCARD__php-fpm__WILDCARD__',
                         'alt-php__WILDCARD__-cli',
                         'alt-php__WILDCARD__-fpm']
EA_WILDCARD_DIR = 'ea-__WILDCARD__'


@functools.cache
def get_universal_hook_path() -> Path:
    """
    Get the path where universal hooks are located.
    """
    if os.path.exists('/etc/dnf/'):
        return UNIVERSAL_HOOK_PATH_DNF
    elif os.path.exists('/etc/apt/'):
        return UNIVERSAL_HOOK_PATH_APT
    else:
        return UNIVERSAL_HOOK_PATH_YUM


def install_multiphp_universal_hook():
    """
    Install universal hook for MultiPHP integration.
    """
    _install_universal_hook(
        MULTIPHP_UNIVERSAL_HOOK_NAME,
        EA_WILDCARD_DIR,
        MULTIPHP_UNIVERSAL_HOOK_SCRIPT,
    )


def remove_multiphp_universal_hook():
    """
    Remove universal hook for MultiPHP integration.
    """
    _remove_universal_hook(MULTIPHP_UNIVERSAL_HOOK_NAME, EA_WILDCARD_DIR)


def install_passenger_universal_hook():
    """
    Install universal hook for ea-apache24-mod-passenger.
    """
    _install_universal_hook(
        PASSENGER_UNIVERSAL_HOOK_NAME,
        EA_WILDCARD_DIR,
        PASSENGER_UNIVERSAL_HOOK_NAME,
    )


def remove_passenger_universal_hook():
    """
    Remove universal hook for ea-apache24-mod-passenger.
    """
    _remove_universal_hook(PASSENGER_UNIVERSAL_HOOK_NAME, EA_WILDCARD_DIR)


def install_without_lve_universal_hooks():
    """
    Install universal hooks for non-LVE environment:
    - trigger after (re)installing/deleting ea-* alt-* packages
      that provide PHP-FPM services.
    """
    for dir_ in PHP_FPM_WILDCARD_DIRS:
        _install_universal_hook(
            PHP_FPM_WITHOUT_LVE_UNIVERSAL_HOOK_NAME,
            dir_,
            PHP_FPM_WITHOUT_LVE_UNIVERSAL_HOOK_SCRIPT,
        )


def remove_without_lve_universal_hooks():
    """
    Remove universal hooks for non-LVE environment.
    """
    for dir_ in PHP_FPM_WILDCARD_DIRS:
        _remove_universal_hook(PHP_FPM_WITHOUT_LVE_UNIVERSAL_HOOK_NAME, dir_)


def _install_universal_hook(hook_name: str, hook_dir: str, script_name: str):
    universal_hook_path = get_universal_hook_path()
    script_path = LIBDIR / script_name  # assuming hook script are in /usr/share/cagefs
    hook_path = universal_hook_path / hook_dir / hook_name
    hook_path.parent.mkdir(parents=True, exist_ok=True)
    if not hook_path.exists():
        hook_path.symlink_to(script_path)


def _remove_universal_hook(hook_name: str, hook_dir: str):
    universal_hook_path = get_universal_hook_path()
    hook_path = universal_hook_path / hook_dir / hook_name
    hook_path.unlink(missing_ok=True)
