import subprocess
import json
import os
from pathlib import Path
import shutil

#hashes = []
#fs = []
mslist = []
class ms:
	hs = ""
	fs = ""
	
	def __repr__(self):
		return (self.tolist())
	
	#def	to_json(self):
	#	return {"name": self.name, "offset": self.offset, "content": self.content, "imports": self.imports, "stringsUsed": self.stringsUsed} 


with open("index.json", "r") as file:
	data = json.load(file)
	for d in data["data"]:
		#hashes.append(d["sha256_hash"])
		#fs.append(d["first_seen"][:4])
		msobj = ms()
		msobj.hs = d["sha256_hash"]
		msobj.fs = d["first_seen"][:4]
		mslist.append(msobj)
#for h in hashes:
for m in mslist:
	subdirectory = f'{m.fs}'
	isExist = os.path.exists(subdirectory)
	if not isExist:
		os.makedirs(subdirectory)
		shutil.copyfile('./FinalScript.py', f'./{subdirectory}/FinalScript.py')
	command = f'wget --post-data "query=get_file&sha256_hash={m.hs}" https://mb-api.abuse.ch/api/v1/ -O {m.hs}'
	subprocess.run(command, cwd=subdirectory, shell=True)

#count = f'ls | wc -l'
for root, dirs, files in os.walk("."):
	#print(dirs)
	for direc in dirs:
		for root2, dirs2, files2 in os.walk(os.path.join(root, direc)):
			for f in files2:
				command2 = f'7z x {f} -pinfected'
				#command2 = f'unzip -P infected {f}'
				subprocess.run(command2, cwd=os.path.join(root, direc), shell=True)
	
		#print(os.path.join(root, name))

#str = "index.html."
#count = 1

#while count < 1000:
#	command = f'7z x {str}{count} -pinfected'
#	subprocess.run(command, shell=True)
#	count += 1

############################################################################################################################

for root, dirs, files in os.walk("."):
	for direc in dirs:
		for root2, dirs2, files2 in os.walk(os.path.join(root, direc)):
			for f in files2:
				#if f.is_file():
				#print(f)
				#fn = file.name
				if f.endswith(".elf") and not f.startswith(("GML", "DOT", "json")):
					#os.system(f"python3 FinalScript.py {f}")
					try:
						subprocess.run(f"python3 FinalScript.py {f}", cwd=os.path.join(root, direc), shell=True, timeout=30)
					except subprocess.TimeoutExpired as e:
						print(e)

# Get the directory (current directory or specified)
#directory = Path.cwd()  # This gets the current working directory

# Or, if you want to specify a different directory, uncomment the line below:
# directory = Path("path/to/directory")

# List all files in the directory
#for file in directory.iterdir():
#    if file.is_file():
#	    #print(file.name)
#	    fn = file.name
#	    if fn.endswith(".elf") and not fn.startswith(("GML", "DOT", "json")):
#		    os.system(f"python3 FinalScript.py {file.name}")

############################################################################################################################