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


class SetKerberosKeys(SetupStep):
    def __init__(self, secret: str):
        super().__init__()
        self.secret = secret

    def run(self, file_cleanup_stack : list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log('Setting Kerberos keys...')
        stdout, stderr, retval = MACHINE_COLLECTION.server.execute_shell_command('samba-tool', 'user', 'setpassword', 'krbtgt', '--newpassword', self.secret)

        if retval != 0:
            log(f'Failed to set krbtgt password: {stderr}', Severity.ERROR)
            return False

        stdout, stderr, retval = MACHINE_COLLECTION.server.execute_shell_command('/usr/share/univention-s4-connector/sync_krbtgt')

        if retval != 0:
            log(f'Sync of krbtgt failed: {stderr if len(stderr) > 0 else stdout}')

        for principal in ['kadmin/changepw', 'kadmin/admin', 'changepw/kerberos', 'kadmin/hprop', 'WELLKNOWN/ANONYMOUS', 'default', 'Guest']:
            log(f'Setting password for principal {principal}', Severity.TRACE)
            stdout, stderr, retval = MACHINE_COLLECTION.server.execute_shell_command(
                'kadmin', '-l', 'passwd', '--random-password', principal)

            if retval != 0:
                log(f'Failed to set password for principal {principal}:{stderr}')
                return False

        log('Successfully set krbtgt password', Severity.DEBUG)
        return True