import logging

import os
import shutil

from defence360agent.utils import OsReleaseInfo

logger = logging.getLogger(__name__)

_DEBIAN_MODSEC_DISABLE_SYMLINK_PATH = (
    "/etc/apache2/plesk.conf.d/i360_modsec_disable.conf"
)
_DEBIAN_MODSEC_DISABLE_SYMLINK = (
    "/etc/apache2/conf-enabled/zz999_modsec2.imunify_disable.conf"
)
_MODSEC_DISABLE_SYMLINK_PATH = (
    "/etc/httpd/conf/plesk.conf.d/i360_modsec_disable.conf"
)
_MODSEC_DISABLE_SYMLINK = (
    "/etc/httpd/conf.d/zz999_modsec2.imunify_disable.conf"
)

_DEBIAN_NEW_MODSEC_DISABLE_FILENAME = (
    "/etc/apache2/plesk.conf.d/i360_modsec_disable.conf"
)
_DEBIAN_OLD_MODSEC_DISABLE_FILENAME = (
    "/etc/apache2/conf/plesk.conf.d/i360_modsec_disable.conf"
)


def migrate(migrator, database, fake=False, **kwargs):
    if fake:
        return
    old_file_name = None
    new_file_name = None
    if OsReleaseInfo.id_like() & OsReleaseInfo.DEBIAN:
        old_file_name = _DEBIAN_OLD_MODSEC_DISABLE_FILENAME
        new_file_name = _DEBIAN_NEW_MODSEC_DISABLE_FILENAME
        symlink_path = _DEBIAN_MODSEC_DISABLE_SYMLINK_PATH
        symlink = _DEBIAN_MODSEC_DISABLE_SYMLINK
    else:
        symlink_path = _MODSEC_DISABLE_SYMLINK_PATH
        symlink = _MODSEC_DISABLE_SYMLINK

    if old_file_name and os.path.exists(old_file_name):
        try:
            shutil.move(old_file_name, new_file_name)
        except Exception:
            logger.exception("Failed move %s", old_file_name)
    if os.path.islink(symlink):
        try:
            os.unlink(symlink)
            os.symlink(symlink_path, symlink)
        except Exception:
            logger.exception("Failed change symlink %s", symlink)


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