import subprocess
import time
import os
from functools import lru_cache
from defence360agent.utils import retry_on, run_with_umask

_SERVICE_NAME = "cagefs"
_COMMAND = "restart"
_CAGEFSCTL_TOOL = "/usr/sbin/cagefsctl"
_WAIT_LOCK = "--wait-lock"


@lru_cache(1)
def systemctl_present(paths=["/usr/bin", "/bin"]):
    """Return whether we can find systemctl in given *paths*."""
    return any(os.path.isfile(os.path.join(p, "systemctl")) for p in paths)


def _restart_cagefs(exc, i):
    if systemctl_present():
        cmd = ["systemctl", _COMMAND, _SERVICE_NAME]
    else:
        cmd = ["service", _SERVICE_NAME, _COMMAND]
    try:
        subprocess.check_call(cmd)
    except Exception:
        pass
    time.sleep(5)


@retry_on(
    subprocess.CalledProcessError,
    max_tries=3,
    on_error=_restart_cagefs,
    silent=True,
)
def _execute_command(cmd):
    subprocess.check_output(cmd, shell=False, stderr=subprocess.STDOUT)


def migrate(migrator, database, fake=False, umask=0o022, **kwargs):
    if fake:
        return
    cmd_list = [
        [_CAGEFSCTL_TOOL, _WAIT_LOCK, "--force-update-etc"],
        [_CAGEFSCTL_TOOL, _WAIT_LOCK, "--remount-all"],
    ]
    with run_with_umask(umask):
        if os.path.exists(_CAGEFSCTL_TOOL):
            for cmd in cmd_list:
                _execute_command(cmd)


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