#!/opt/cloudlinux/venv/bin/python3 -bb
# -*- coding: utf-8 -*-
"""
This script used for apply cpanel package changes to lve config
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import sys
import time
import traceback

from clcommon.cpapi import is_panel_feature_supported, Feature
from clcommon.utils import is_root_or_exit

import cldetectlib as detect
import lvectllib

LIBDIR = "/usr/share/l.v.e-manager/cpanel/lib"
SCRIPT_NAME = __file__.split("/")[-1]

sys.path.append(LIBDIR)
import packages
from packages import save_package, LVE_CONFIG, PKG_DIR, QUOTA_CONFIG, MYSQLGOV_PACKAGES_CONFIG
from clcommon.lib.cledition import lve_supported_or_exit
import logging
import logging.handlers


def setup_system_log():
    """
    Sets syslog logger and returns its handler
    """
    syslogger = logging.handlers.SysLogHandler(address='/dev/log')
    syslogger.setFormatter(logging.Formatter(fmt='%(levelname)s %(message)s'))
    logger = logging.getLogger(SCRIPT_NAME)
    logger.setLevel(logging.INFO)
    logger.addHandler(syslogger)
    # save_package() reports package limits it cannot read. Without a handler
    # here those records reach nothing, and the omission stays invisible in
    # /var/log/messages (CLOS-7037).
    packages.logger.setLevel(logging.INFO)
    packages.logger.addHandler(syslogger)
    return logger


def _get_file_mtime(filename: str) -> float:
    """
    Get file mtime, or +inf when the file does not exist.

    The references are OR-ed, so +inf means a reference that is not on disk
    simply never opens the gate by itself; the other references still can.
    Returning -inf instead opens it for every package on every run.

    @param filename:
    @return: mtime
    """
    if os.path.exists(filename):
        return os.path.getmtime(filename)
    return float("inf")


def _packages_in_lve_config() -> set:
    """
    Ids of the <package> elements ve.cfg already holds.

    @return: set of package names
    """
    return {element.getAttribute('id') for element in lvectllib.ve_package}


def _should_process_package(pkg_mtime: float, reference_mtimes,
                            in_lve_config: bool) -> bool:
    """
    Decide whether a package file has to be synced.

    The mtime references are the ones this sync itself moves forward, so they
    only answer "was this package edited recently". A package that fell out of
    ve.cfg can never win that comparison again, and stays missing until someone
    touches its file by hand - so its absence decides on its own (CLOS-9123).

    @param pkg_mtime: mtime of the cPanel package file
    @param reference_mtimes: mtimes the package file is compared against
    @param in_lve_config: whether ve.cfg already carries this package
    @return: True when the package has to be synced
    """
    if not in_lve_config:
        return True
    return any(pkg_mtime > reference for reference in reference_mtimes)


def main():
    is_root_or_exit()
    if not detect.is_cpanel():
        sys.exit(0)
    logger = setup_system_log()
    try:
        if is_panel_feature_supported(Feature.LVE):
            lvectllib.init()
            lvectllib.get_XML_cfg()

        current_time = time.time()
        lve_mtime, quotas_mtime, governor_mtime = current_time, current_time, current_time
        # None means "ve.cfg does not apply here", so the mtime gate alone decides.
        synced_packages = None

        if is_panel_feature_supported(Feature.LVE):
            lve_mtime = os.path.getmtime(LVE_CONFIG)
            synced_packages = _packages_in_lve_config()

        quotas_mtime = _get_file_mtime(QUOTA_CONFIG)

        if is_panel_feature_supported(Feature.GOVERNOR):
            governor_mtime = _get_file_mtime(MYSQLGOV_PACKAGES_CONFIG)
    except Exception as e:
        logger.error(e)
        sys.exit(1)

    minute_before = current_time - 60.0 * 5
    exit_status = 0
    for pkg_name in os.listdir(PKG_DIR):
        file_path = os.path.join(PKG_DIR, pkg_name)
        if not os.path.isfile(file_path):
            continue
        pkg_mtime = os.path.getmtime(file_path)
        references = (minute_before, lve_mtime, quotas_mtime, governor_mtime)
        in_lve_config = synced_packages is None or pkg_name in synced_packages
        if _should_process_package(pkg_mtime, references, in_lve_config):
            try:
                # Only a package that was really written is reported, so the
                # line stays rare: packages with no lve extension are missing
                # from ve.cfg on every run and must not fill the log.
                if save_package(pkg_name) and not in_lve_config:
                    logger.info('package %s was missing from %s and has been '
                                'synced back', pkg_name, LVE_CONFIG)
            except Exception:
                exit_status = 1
                msg = traceback.format_exc()
                logger.error(f'Error while processing package data file {file_path}:\n{msg}\n')
                continue
    sys.exit(exit_status)


if "__main__" == __name__:
    main()
