from random import choice
from string import ascii_lowercase

from ...Logging.Logger import log, Severity
from ...Machine.PaedMLMachineCollection import MACHINE_COLLECTION, LMZ_COMMON_CREDENTIALS
from ...SetupSteps.Playbooks.Playbook import FileCleanupTask, PlaybookCredentialCollection
from ...SetupSteps.SetupStep import SetupStep


class SetupSso(SetupStep):
    def run(self, file_cleanup_stack: list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log('Setting up SSO on backup...')
        backup = MACHINE_COLLECTION.backup

        backup.delete(f'/usr/share/univention-management-console/saml/idp/login.{LMZ_COMMON_CREDENTIALS.get_domainname()}.xml')

        domadmin_temp_file = f'/tmp/{"".join(choice(ascii_lowercase) for i in range(5))}'
        backup.write_file(domadmin_temp_file, credentials.domadmin.encode('utf-8'))
        file_cleanup_stack.append(FileCleanupTask(backup, domadmin_temp_file))

        stdout, stderr, retval = backup.execute_shell_command('/usr/sbin/univention-run-join-scripts',
                                     '-dcaccount', 'domadmin',
                                     '-dcpwd', domadmin_temp_file,
                                     '--force',
                                     '--run-scripts', '92univention-management-console-web-server.inst')
        if retval != 0:
            log(f'Failed to run join script: {stderr if len(stderr) != 0 else stdout}')
            return False

        stdout, stderr, retval = backup.execute_shell_command('systemctl', 'restart', 'univention-management-console-server.service')
        if retval != 0:
            log(f'Failed to restart univention management console server: {stderr if len(stderr) != 0 else stdout}')
            return False

        stdout, stderr, retval = backup.execute_shell_command('systemctl', 'restart', 'univention-management-console-web-server.service')
        if retval != 0:
            log(f'Failed to restart univention management console web server: {stderr if len(stderr) != 0 else stdout}')
            return False