"""
Remove /var/cpanel/templates/apache2_4/ea4_main.local file
introduced by imunify360. This file was used to change apache log format
(%h->%a), when imunify360 installed remote_ip apache module.

Since this file is created once it can be outdated after updating cPanel (
in case if /var/cpanel/templates/apache2_4/ea4_main.default also updated).

See DEF-9641 for details.
"""
import logging
from pathlib import Path
import subprocess

from defence360agent.utils import antivirus_mode

logger = logging.getLogger(__name__)

EA4_MAIN_LOCAL_PATH = Path("/var/cpanel/templates/apache2_4/ea4_main.local")
EA4_MAIN_DEFAULT_PATH = Path(
    "/var/cpanel/templates/apache2_4/ea4_main.default"
)

NEW = "%a "
OLD = "%h "


@antivirus_mode.skip
def migrate(
    migrator,
    database,
    fake=False,
    default_conf_path=EA4_MAIN_DEFAULT_PATH,
    local_conf_path=EA4_MAIN_LOCAL_PATH,
    **kwargs
):
    if fake:
        return

    from im360.subsys.panels.cpanel import cPanel

    try:
        if cPanel.is_installed() and local_conf_path.exists():
            origin_text = default_conf_path.read_text()
            restored_text = local_conf_path.read_text().replace(NEW, OLD)
            # assume that these changes were made by imunify360
            if restored_text == origin_text:
                # remove file and rebuild confs
                local_conf_path.unlink()
                subprocess.check_call(cPanel.REBUILD_HTTPDCONF_CMD)
    except Exception as exc:
        logger.error("Can't remove %s, reason: %s", local_conf_path, exc)


def rollback(migrator, database, fake=False, **kwargs):
    pass
