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


class TriggerUcsPasswordChange(SetupStep):
    def __init__(self, machine: MachineInterface):
        super().__init__()
        self.machine = machine

    def run(self, file_cleanup_stack : list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log(f'Triggering UCS password change on {self.machine.get_hostname()}. This may take a while...')
        self.machine.move('/etc/krb5.keytab', '/etc/krb5.keytab.SAVE')
        self.machine.write_file('/etc/krb5.keytab', b'')
        stdout, stderr, retval = self.machine.execute_shell_command('ucr', 'set', '--force', 'server/password/interval=1')
        if retval != 0:
            log(f'Error setting UCR variable: {stderr}', Severity.ERROR)
            return False

        stdout, stderr, retval = self.machine.execute_shell_command('touch', '-t', '197001010000', '/etc/machine.secret')
        if retval != 0:
            log(f'Error setting file date for machine secret: {stderr}', Severity.ERROR)
            return False

        stdout, stderr, retval = self.machine.execute_shell_command('/usr/lib/univention-server/server_password_change')
        if retval != 0:
            log(f'Error executing password change script: {stderr}', Severity.ERROR)
            return False

        stdout, stderr, retval = self.machine.execute_shell_command('ucr', 'unset', '--force', 'server/password/interval')
        if retval != 0:
            log(f'Error un-setting UCR variable: {stderr}', Severity.ERROR)
            return False

        return True