import shlex

from ...Machine.MachineInterface import MachineInterface
from ...Logging.Logger import log, Severity
from ...SetupSteps.Playbooks.Playbook import FileCleanupTask, PlaybookCredentialCollection
from ...SetupSteps.SetupStep import SetupStep


class UcsRepositorySetup(SetupStep):
    def __init__(self, machine: MachineInterface, repo_name: str, repo_server: str):
        super().__init__()
        self.machine = machine
        self.repo_name = repo_name
        self.repo_server = repo_server

    def run(self, file_cleanup_stack : list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log(f'Setting up {self.repo_name} repository on {self.machine.get_hostname()}...', Severity.INFO)

        log('Restarting univention-directory-policy...', Severity.DEBUG)
        stdout, stderr, retval = self.machine.execute_shell_command('systemctl', 'restart', 'univention-directory-policy')
        if retval != 0:
            log(f'Failed to restart univention-directory-policy: {stderr}', Severity.ERROR)
            return False

        log('Removing old repository components...', Severity.DEBUG)
        stdout, stderr, retval = self.machine.execute_shell_command('ucr', 'unset',
                                                                    f'repository/online/component/{self.repo_name}/username',
                                                                    f'repository/online/component/{self.repo_name}/password',
                                                                    f'repository/online/component/extsec5.0/username',
                                                                    f'repository/online/component/extsec5.0/password',
                                                                    f'repository/online/component/extsec5.0')
        if retval != 0:
            log(f'Failed to remove old repository components: {stderr}', Severity.ERROR)
            return False

        log('Adding new repository components...', Severity.DEBUG)
        repo_component = shlex.quote(f'https://{credentials.mli}:{credentials.mli_password}@{self.repo_server}')
        stdout, stderr, retval = self.machine.execute_shell_command('ucr', 'set',
                                                                    f'repository/online/component/{self.repo_name}=yes',
                                                                    f'repository/online/component/{self.repo_name}/server={repo_component}')
        if retval != 0:
            log(f'Failed to set repository: {stderr}', Severity.ERROR)
            return False
        return True