"""Using ModSecurity 'WordPress login attempt' rule instead of OSSEC one.
This migration is needed in order to add new rule to config after update,
because config is non replaceable.
"""
import os
import shutil

from defence360agent.contracts.config import IConfigFile, LocalConfig

SECTION = "MOD_SEC_BLOCK_BY_CUSTOM_RULE"
RULE_ID = "33332"  # WordPress login attempt
RULE_VALUES = {"max_incident_repetition": 10, "check_period": 120}


def migrate(migrator, database, fake=False, **kwargs):
    if fake:
        return

    local_config: IConfigFile = LocalConfig()
    if not os.path.exists(local_config.path):
        return
    if not os.path.isfile(local_config.path):
        return
    shutil.copyfile(local_config.path, local_config.path + ".old")
    new_conf = local_config.config_to_dict()
    new_conf.setdefault(SECTION, {})[RULE_ID] = RULE_VALUES
    local_config.dict_to_config(new_conf, validate=False)


def rollback(migrator, database, fake=False, **kwargs):
    if fake:
        return
    local_config: IConfigFile = LocalConfig()
    old = local_config.path + ".old"
    if os.path.isfile(old):
        shutil.move(old, local_config.path)
