# -*- coding:utf-8 -*-
import os
import boto3
from boto3.session import Session
from cuckoo import CUCKOO_API
import time

ACCESS_KEY = os.environ.get('ACCESS_KEY')
SECRET_KEY = os.environ.get('SECRET_KEY')
DOWNLOAD_PATH = os.environ.get('DOWNLOAD_PATH')
BUCKET_NAME = os.environ.get('BUCKET_NAME')

session = Session(aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY)
s3 = session.resource('s3')
buckets = s3.Bucket(BUCKET_NAME)

CUCKOO = CUCKOO_API()

for bucket in s3.buckets.all():
    for obj in bucket.objects.filter(Prefix='vxvault/'):
        fileName = obj.key.split('_')[-1]
        filePath = '{}/{}'.format(DOWNLOAD_PATH,fileName)
        s3 = boto3.resource('s3')
        s3.Bucket(BUCKET_NAME).download_file(obj.key,filePath)
    

        while True:
            '''Check the state of sandbox'''
            data = CUCKOO.machine_view()
            machine = ''


            '''Check unused sandbox'''
            for i in range(len(data['machines'])):
                if data['machines'][i]['status'] != "running":
                    machine = data['machines'][i]['name']
                    break
                else:
                    continue
            

            '''Re-check if there is not available sandbox for analyzing'''
            if len(machine) == 0:
                time.sleep(4)
                continue

            
            else:
                ''' Transfer malware to sandbox if there is idle sandbox for analyzing '''
                CUCKOO.create_request(filePath,machine)
                # print ("[+] {} : {}".format(machine,filePath.split('/')[-1]))
                time.sleep(5.5)
                break

