from settings import Settings
import util_marshal
from attacker import Attacker
import json
import time
import importlib
from submitter import CustomSubmitter


def import_modules(settings, caller_globals):
    modules_list = settings['exploit_modules']
    for module in modules_list:
        caller_globals[module] = importlib.import_module(module)


def run_exploits(exploit_in, settings, caller_globals, thread_struct, queued_submitter):
    exploit_in = util_marshal.unserialize_exploit(exploit_in, caller_globals)
    try:
        opponents = exploit_in['opponents'] if len(exploit_in['opponents']) > 0 else\
            settings.configuration['attack']['targets']
    except KeyError:
        opponents = settings.configuration['attack']['targets']
    try:
        exploit_type = exploit_in['type']
    except KeyError:
        exploit_type = 'return'
        print("[+] Exploit type not found; default to return")
    service = exploit_in['service']
    if service not in thread_struct:
        thread_struct[service] = {}
    else:   # overwrite threads for the service and opponents specified
        for opponent in thread_struct[service].keys():
            thread_struct[service][opponent].kill()
    for opponent in opponents:
        attacker = Attacker(settings, opponent, service, exploit_in['exploit'], caller_globals,
                            exploit_type, queued_submitter)
        attacker.start()
        thread_struct[service][opponent] = attacker
        # {'lost property hub': {'10.10.0.1': thread1, '10.10.0.2': thread2}, 'blabla': {'10.10.0.1': thread3}}


def load_setup(caller_globals):
    settings = Settings("./volume/conf.json")
    import_modules(settings.configuration, caller_globals)
    CustomSubmitter(settings, caller_globals)
    return settings


if __name__ == '__main__':
    settings = load_setup(globals())
    print(globals())
    with open('simple_exploit.JSON', 'r') as f:
        exploit = json.load(f)
    t_struct = {}
    run_exploits(exploit, settings, globals(), t_struct, None)
    run_exploits(exploit, settings, globals(), t_struct, None)
    time.sleep(60)
