import logging

import os
import shutil

from defence360agent.utils import OsReleaseInfo

logger = logging.getLogger(__name__)

_DEBIAN_NEW_MODSEC_DISABLE_FILENAME = (
    "/etc/apache2/conf/plesk.conf.d/i360_modsec_disable.conf"
)
_DEBIAN_OLD_MODSEC_DISABLE_FILENAME = (
    "/etc/apache2/conf/plesk.conf.d/vhosts/i360_modsec_disable.conf"
)
_NEW_MODSEC_DISABLE_FILENAME = (
    "/etc/httpd/conf/plesk.conf.d/i360_modsec_disable.conf"
)
_OLD_MODSEC_DISABLE_FILENAME = (
    "/etc/httpd/conf/plesk.conf.d/vhosts/i360_modsec_disable.conf"
)


def migrate(migrator, database, fake=False, **kwargs):
    if fake:
        return
    if OsReleaseInfo.id_like() & OsReleaseInfo.DEBIAN:
        old_file_name = _DEBIAN_OLD_MODSEC_DISABLE_FILENAME
        new_file_name = _DEBIAN_NEW_MODSEC_DISABLE_FILENAME
    else:
        old_file_name = _OLD_MODSEC_DISABLE_FILENAME
        new_file_name = _NEW_MODSEC_DISABLE_FILENAME

    if 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)


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