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

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

    def run(self, file_cleanup_stack : list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        machine = MACHINE_COLLECTION.backup
        log('Installing Opsi License...', Severity.INFO)
        log('Unpacking opsilic...', Severity.TRACE)
        stdout, stderr, retval = machine.execute_shell_command('tar', 'xvzf', '/etc/opsi/licenses/opsilic.tar.gz', '-C', '/etc/opsi/licenses')
        if retval != 0:
            log('Failed to unpack opsilic.', Severity.ERROR)
            return False

        log('Restarting opsiconfd...')
        stdout, stderr, retval = machine.execute_shell_command('systemctl', 'restart', 'opsiconfd.service')
        if retval != 0:
            log('Opsiconfd did not restart.', Severity.ERROR)
            stdout, stderr, retval = machine.execute_shell_command('systemctl', 'status', 'opsiconfd.service')
            log(f'Status:\n{stdout}', Severity.ERROR)
            return False
        return True