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


class RegenerateVeyonKeys(SetupStep):
    def __init__(self):
        super().__init__()

    def run(self, file_cleanup_stack: list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log('Regenerating Veyon keys...')

        join_status = MACHINE_COLLECTION.server.read_file('/var/univention-join/status')
        join_lines = []
        for line in join_status.decode('utf-8').splitlines():
            if not line.startswith('ucs-school-veyon-windows '):
                join_lines.append(line)
        new_join_status = '\n'.join(join_lines)
        MACHINE_COLLECTION.server.write_file('/var/univention-join/status', new_join_status.encode('utf-8'))

        MACHINE_COLLECTION.server.delete('/etc/ucsschool-veyon/cert.pem')
        MACHINE_COLLECTION.server.delete('/etc/ucsschool-veyon/key.pem')

        stdout, stderr, retval = MACHINE_COLLECTION.server.execute_shell_command('/usr/lib/univention-install/37ucs-school-veyon-windows.inst')
        if retval != 0:
            log(f'Failed to execute joinscript: {stderr}')
            return False

        return True