#!/usr/bin/python3
# -*- coding: utf-8 -*-
# pylint: disable=line-too-long,too-many-lines

""" buildscript """

from pprint import pprint
import time
import os

import yaml
import requests

import PyInstaller.__main__

with open("config.yml", "r", encoding="UTF-8") as ymlfile:
    cfg = yaml.load(ymlfile, Loader=yaml.Loader)

apikey = cfg['virustotal']

PyInstaller.__main__.run(['tts.py', '--onefile',])

os.replace("./dist/tts.exe", "./tts.exe")

print("Uploading file")
api_endpoint = "https://www.virustotal.com/api/v3/files" # pylint: disable=invalid-name
headers = {
    "Accept": "application/json",
    "X-Apikey": apikey
}
files = {"file": open("./tts.exe", "rb")}
req = requests.post(api_endpoint, headers=headers, files=files)
print(" [OK]")

data = {}
data['data'] = {}
data['data']['attributes'] = {}
data['data']['attributes']['status'] = "incomplete"

print("Waiting for results")
while data['data']['attributes']['status'] != "completed":
    time.sleep(10)

    print( " [CHK]")
    data = req.json()
    api_endpoint = f"https://www.virustotal.com/api/v3/analyses/{data['data']['id']}"
    headers = {
        'X-Apikey': apikey
    }
    req = requests.get(api_endpoint, headers=headers)
    data = req.json()

print(" [OK]")

try:
    pprint(data['data']['attributes']['results']['Microsoft'])
except KeyError:
    pass

pprint(data['data']['attributes']['stats'])
print("https://www.virustotal.com/gui/file/"+str(data['meta']['file_info']['sha256']))

try:
    if data['data']['attributes']['results']['Microsoft']['category'] != "undetected":
        print('FILE WILL BE DETECTED AS MALICIOUS. PLEASE RECOMPILE!')
except KeyError:
    pass
