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


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

    def run(self, file_cleanup_stack : list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log('Writing new RADIUS secret...')
        current_config = MACHINE_COLLECTION.server.read_file('/etc/freeradius/3.0/clients.conf').decode()
        new_config = ''
        for line in current_config.splitlines(True):
            if line.strip().startswith('#'):
                new_config += line
                continue
            if line.strip().startswith('secret = '):
                log('Found old password - replacing...', Severity.DEBUG)
                new_config += f'secret = "{self.secret}"\n'
                continue
            new_config += line

        MACHINE_COLLECTION.server.write_file('/etc/freeradius/3.0/clients.conf', new_config.encode())
        return True