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


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

    def run(self, file_cleanup_stack : list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log(f'Writing MLI to disk on {self.machine.get_hostname()}...', Severity.INFO)

        try:
            log('Writing /etc/kdn.user...', Severity.TRACE)
            self.machine.write_file('/etc/kdn.user', credentials.mli.encode('utf-8'))
            log('Writing /etc/kdn.secret...', Severity.TRACE)
            self.machine.write_file('/etc/kdn.user', credentials.mli.encode('utf-8'))
        except Exception as e:
            log(f'Failed to write MLI: {e}', Severity.ERROR)
            return False

        stdout, stderr, retval = self.machine.execute_shell_command('chmod', '600', '/etc/kdn.user', '/etc/kdn.secret')
        if retval != 0:
            log(f'Failed to set permissions for MLI files: {stderr}', Severity.ERROR)
            return False

        return True