from sys import stderr

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


class ApplyFreeradiusCert(SetupStep):
    def run(self, file_cleanup_stack: list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log('Applying FreeRADIUS certificate...')
        server = MACHINE_COLLECTION.server

        server.delete('/etc/freeradius/ssl/private.key')
        server.delete('/etc/freeradius/ssl/cert.pem')

        server.write_file('/etc/freeradius/ssl/private.key',
                          server.read_file(f'/etc/univention/ssl/{server.get_hostname()}/private.key'))
        server.write_file('/etc/freeradius/ssl/cert.pem',
                          server.read_file(f'/etc/univention/ssl/{server.get_hostname()}/cert.pem'))

        stdout, stderr, retval = server.execute_shell_command('chgrp', 'freerad', '/etc/freeradius/ssl/private.key', '/etc/freeradius/ssl/cert.pem')
        if retval != 0:
            log(f'Failed to chgrp certificates: {stderr}', Severity.ERROR)
            return False

        stdout, stderr, retval = server.execute_shell_command('chmod', '400', '/etc/freeradius/ssl/private.key',
                                                              '/etc/freeradius/ssl/cert.pem')
        if retval != 0:
            log(f'Failed to chmod certificates: {stderr}', Severity.ERROR)
            return False

        stdout, stderr, retval = server.execute_shell_command('openssl', 'dhparam', '-out', '/etc/freeradius/ssl/dh', '1024')
        if retval != 0:
            log(f'Failed to generate Diffie-Hellman parameters: {stderr}', Severity.ERROR)
            return False

        return True