import os
import hashlib
import random

from modules.malware.malware import call_url
from modules.malware.malware import obfuscate

from faker import Faker
from faker.providers import internet

# instantiate faker
fake = Faker()
fake.add_provider(internet)

malware_output = "output/malware"


def make_malware(c2_domains):
    '''
    takes in list of command and control urls (either as invidual args or as a list)
    generates obsfuscated powershell malware in the output folder
    c2_urls must be a list
    '''

    for level, domain in enumerate(c2_domains):
        #url = gen_malware_link()
        input = call_url(domain)
        malware = obfuscate(input=input, num=level+1)
        filename = "%s_%s" % (level, str(get_hash(malware)))
        write_to_file(malware, filename)


def write_to_file(content, filename):
    filepath = os.path.join(malware_output, filename)
    with open(filepath, 'w+') as f:
        f.write(content)


def get_hash(val):
    hash = hashlib.sha1(str(val).encode('utf-8'))
    return hash.hexdigest()


def gen_malware_link():
    """Generate random strings of three words for dummy url"""
    # thanks to: https://www.geeksforgeeks.org/python-remove-all-characters-except-letters-and-numbers/
    import re

    WORD_CLOUD = ["account", "site", "user", "microsoft", "twitter", "it", "reset", "download", "org", "digital",
              "invoice", "payment", "secure", "notice", "critical", "financial", "bank", "service",
              "business", "portal", "browse", "legit", "defender", "login", "share", "amazon", "device"]

    pre = random.choice(["http://", "https://"])
    tld = fake.tld()
    domain = "".join(random.sample(WORD_CLOUD, 3))
    request = fake.slug() + ".exe"

    link = pre + domain + tld + "/" + request

    return link