# !/bin/python
# -*- coding: utf-8 -*-
u"""SecureTea Social Engineering
Project:
    ╔═╗┌─┐┌─┐┬ ┬┬─┐┌─┐╔╦╗┌─┐┌─┐
    ╚═╗├┤ │  │ │├┬┘├┤  ║ ├┤ ├─┤
    ╚═╝└─┘└─┘└─┘┴└─└─┘ ╩ └─┘┴ ┴
    Author: Digvijay Bhosale <digvijayb1729@gmail.com> August 15 2021
    Version: 1.0
    Module: SecureTea
"""

import os
import json
import subprocess

from securetea.lib.malware_analysis.fileAnalysis import FileAnalyser
from securetea.lib.malware_analysis.malwareAnalysis import MalwareAnalysis
from securetea.lib.malware_analysis.continuous_malware_defence import ContinuousDefence
from securetea.lib.malware_analysis import globals
from securetea.lib.malware_analysis.mal_gui import app_runner


'''
def boom():
    # Create new threads
    GUI = input('Would you like GUI? (Y/n) \n\t:') or 'y'
    if GUI.lower() == 'n':
        GUI = False
    else:
        GUI = True

    globals.initialize_flask()
    thread1 = ContinuousDefence(gui=GUI)

    # Start new Thread for MalwareAnalysis
    thread1.start()
    if GUI:
        app_runner()

    thread1.join()


boom()
'''


'''
i = 0
filename = ''
same_file = 'n'

if __name__ == '__main__':
    globals.initialize_colours()
    while True:
        if i == 1:  # so that this will run after the first loop runs
            try:
                same_file = input('Use same file? (Y/n)') or 'y'  # makes UX better by not making select same file again
            except KeyboardInterrupt:
                print(globals.WARNING + "KeyboardInterrupt Detected. Quitting now ..." + globals.END)

        if same_file.lower() == 'n':  # get new file if user wants new file
            filename = ''
            i = 0
            try:
                cont_defence = input("Continuous Malware Analysis (c/C) or Individual File Analysis (i/I) (Default i/I) : ") or 'i'
                if cont_defence.lower() == 'c':
                    cont_defence_obj = ContinuousDefence()
                    cont_defence_obj.runner()
                    exit(0)
                else:
                    filename = input("File to check for malware (Enter complete path if file not in directory of script) : ")
            except KeyboardInterrupt:
                print(globals.WARNING + "KeyboardInterrupt Detected. Quitting now ..." + globals.END)
                exit(0)

            if filename.lower().strip() == 'q' or filename.lower() == 'quit' or filename.lower() == 'exit':
                print("Thank you for using SecureTea Malware Analysis Tool")
                exit()

            if os.path.isfile(filename):
                pass
            else:
                print(globals.WARNING + 'Given Filename does not exist. ' + globals.END)
                continue

        action = ''
        try:
            action = input('f/F - Steganographic File Analysis of Suspicious file\n'
                           'm/M - Malware Analysis of Suspicious file\n'
                           'a/A - Steg and Malware analysis\n'
                           'q/Q - Quit\n'
                           '\t:')
        except KeyboardInterrupt:
            print(globals.WARNING + "KeyboardInterrupt Detected. Quitting now ..." + globals.END)
            exit(0)

        if action.lower() == 'f':
            f_analysis = FileAnalyser(filename)
            f_analysis.start_analysis()
        elif action.lower() == 'm':
            m_analysis = MalwareAnalysis(filename)
            m_analysis.runner()
        elif action.lower() == 'a':
            f_analysis = FileAnalyser(filename)
            f_analysis.start_analysis()
            m_analysis = MalwareAnalysis(filename)
            m_analysis.runner()
        elif action.lower() == 'q':
            print("Thank you for using SecureTea Malware Analysis Tool")
            exit()
        else:
            print(globals.WARNING + 'Incorrect Option selected' + globals.END)

        i = 1  # after first loop, i =1
'''


class SecureTeaMalwareAnalysis:
    def __init__(self, creds):
        self.mode = creds['mode']
        self.api_key = ''
        self.filename = ''
        globals.initialize_colours()

    def runner(self):
        if self.mode.lower() == 'i' or self.mode.lower() == 'm':
            while True:
                self.filename = input("Enter Filename\n\t:")
                if os.path.isfile(self.filename):
                    break
                else:
                    print(globals.WARNING + 'Given Filename does not exist. ' + globals.END)

        if self.mode.lower() == 'c' or self.mode.lower() == 'm':
            c = input('Check API_KEY Validity? (y/N)') or 'N'
            if c.lower() == 'y':
                while True:
                    api_key = input("Enter API_KEY\n\t:")
                    validity_code = self.check_api_key(api_key=api_key)
                    if validity_code == 0:
                        print("API KEY Valid")
                        self.api_key = api_key
                        break
                    elif validity_code == 1:
                        print("API KEY Invalid")
                    elif validity_code == 2:
                        print("secureta/lib/notifs/val_file/cat.jpg seems to be missing....\n"
                              "If cat.jpg is missing, create a cat.jpg file (Download from the internet is easiest")
                    elif validity_code == 3:
                        print("Some unknown error occurred")
                    else:
                        print("Some error with the API Occurred")
            else:
                print("Validity of API KEY will not be checked.")
                self.api_key = input("Enter API_KEY\n\t:")

        if self.mode.lower() == 'c':
            GUI = True
            globals.initialize_flask()
            thread1 = ContinuousDefence(gui=GUI, API_KEY=self.api_key)

            # Start new Thread for MalwareAnalysis
            thread1.start()
            if GUI:
                app_runner()

            thread1.join()
        elif self.mode.lower() == 'i':
            f_analysis = FileAnalyser(self.filename)
            f_analysis.start_analysis()
        elif self.mode.lower() == 'm':
            m_analysis = MalwareAnalysis(filename=self.filename, API_KEY=self.api_key)
            m_analysis.runner()
        else:
            print("Incorrect option selected")
            return

    def check_api_key(self, api_key):
        API_KEY = api_key
        filename = './val_file/cat.jpg'
        base_url = 'https://www.virustotal.com/api/v3/files'
        headers = 'x-apikey: ' + API_KEY
        file_path = '@' + filename

        process = subprocess.Popen(['curl', '--request', 'POST', '--url', base_url,
                                    '--header', headers,
                                    '--form', 'file=' + file_path],
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        data = stdout.decode('utf-8')
        stderr = stderr.decode('utf-8')
        try:
            json_data = json.loads(data)
        except json.decoder.JSONDecodeError:
            # file val_file/cat.jpg missing
            return 2
        # print(json_data.keys[1])
        if 'data' in json_data.keys():
            return 0
        elif 'error' in json_data.keys():
            if json_data['error']['code'] == 'WrongCredentialsError':
                return 1
        else:
            return 3


