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


class CopyCertificates(SetupStep):
    def copy_cert_file(self, filename):
        base_path = f'/etc/univention/ssl/{MACHINE_COLLECTION.backup.get_hostname()}/'
        file = MACHINE_COLLECTION.server.read_file(f'{base_path}{filename}')
        MACHINE_COLLECTION.backup.write_file(f'{base_path}/{filename}', file)


    def run(self, file_cleanup_stack: list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log('Copying certificates to opsi server...')
        backup = MACHINE_COLLECTION.backup
        server = MACHINE_COLLECTION.server

        backup.delete('/etc/univention/ssl.orig')
        backup.move('/etc/univention/ssl', '/etc/univention/ssl.orig')

        stdout, stderr, retval = server.execute_shell_command('ucr', 'get', 'ssl/common')
        if retval != 0:
            log(f'Failed to read ssl/common: {stderr}', Severity.ERROR)
            return False

        common_name = stdout.strip()

        stdout, stderr, retval = backup.execute_shell_command('ucr', 'set', f'ssl/common={common_name}')
        if retval != 0:
            log(f'Failed to set ssl/common: {stderr}', Severity.ERROR)
            return False

        backup.mkdir(f'/etc/univention/ssl/{backup.get_hostname()}')
        backup.execute_shell_command('chmod', '750', f'/etc/univention/ssl/{backup.get_hostname()}')
        backup.execute_shell_command('ln', '-s', f'/etc/univention/ssl/{backup.get_hostname()}', f'/etc/univention/ssl/{backup.get_hostname_short()}')

        for filename in ['cert.pem', 'openssl.cnf', 'private.key', 'req.pem']:
            log(f'Copying {filename}', Severity.TRACE)
            self.copy_cert_file(filename)

        log('Copying CAcert.pem', Severity.TRACE)
        cacert = server.read_file('/etc/univention/ssl/ucsCA/CAcert.pem')
        backup.mkdir('/etc/univention/ssl/ucsCA')
        backup.write_file('/etc/univention/ssl/ucsCA/CAcert.pem', cacert)
        backup.write_file('/var/lib/opsi/depot/zertifikat/CAcert.pem', cacert)
        opsi_ca = backup.read_file('/etc/ssl/certs/opsi_CA.pem')
        backup.write_file('/var/lib/opsi/depot/zertifikat/opsi_CA.pem', opsi_ca)

        log('Setting permissions on opsi server...', Severity.DEBUG)
        stdout, stderr, retval = backup.execute_shell_command('chown', '-R', 'root:root', '/etc/univention/ssl')
        if retval != 0:
            log(f'Failed to set permissions on opsi server: {stderr}')
            return False
        stdout, stderr, retval = backup.execute_shell_command('opsi-set-rights')
        if retval != 0:
            log(f'Failed to execute opsi-set-rights: {stderr}')
            return False

        #stdout, stderr, retval = backup.execute_shell_command('/usr/share/lmz-zertifikat-permissions')
        #if retval != 0:
        #    log(f'Failed to set lmz certificate permissions: {stderr if len(stderr) > 0 else stdout}', Severity.ERROR)
        #    return False



        log('Certificates copied successfully.', Severity.DEBUG)
        return True