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 CreateSpnAccount(SetupStep):
    def __init__(self, account_name: str, principal_name: str, keytab: str):
        super().__init__()
        self.account_name = account_name
        self.principal_name = principal_name
        self.keytab = keytab

    def run(self, file_cleanup_stack : list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        log(f'Creating SPN Account for {self.account_name}')
        stdout, stderr, retval = MACHINE_COLLECTION.server.execute_shell_command(
            '/usr/share/univention-samba4/scripts/create_spn_account.sh',
            '--samaccountname', self.account_name,
            '--serviceprincipalname', self.principal_name,
            '--privatekeytab', self.keytab
        )

        if retval == 0:
            log("Success.", Severity.DEBUG)
            return True

        log(f"Failed to add SPN Account: {stderr if len(stderr) > 0 else stdout}", Severity.ERROR)
        return False