import os
import shutil
import time, datetime
import tabulate

import subprocess

times = []
tests = [
    "test8", "test9", "test10", "test11", "test12", "test6", "test7", 
]

test_description = [
    ("nop lw", "mem"),
    ("nop lw", "mem, regs"),
    ("nop alui lw", "mem"),
    ("nop sw lw", "mem"),
    ("nop lw lw", "regs"),
    ("nop (lw + alui) (lw + alui) sw", "mem, regs"),
    ("nop (lw + alui) (lw + alui) (lw + alui) sw", "mem, regs")
]

test_dir = f"{os.getcwd()}/riscv-sodor-model/verification/sodor_security/"

dut_dir = "sec_taskBMC20_sodor5_lb_u"
mod_dir = "sec_taskBMC20_sodor5_model_lb_u"

for i, test in enumerate(tests):
    print("Running test: " + test)
    shutil.copyfile(f"{test_dir}/{test}/sodor5_lb_unified_bmc.v", f"{test_dir}/sodor5_lb_unified_bmc.v")
    
    # Test with design
    pretime = time.time()
    p = subprocess.run(['time', 'sby', '-f', 'sec.sby', 'taskBMC20_sodor5_lb_u'], cwd=test_dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    s = p.stdout.decode('utf-8')
    print(s)
    r_dut = "DONE (PASS" in s
    posttime = time.time()
    dut_time = posttime - pretime
    print(f"For test: {test} DUT time: {dut_time}")

    # Save the results
    os.system(f"cp -r {test_dir}/{dut_dir} {test_dir}/{test}")

    # Test on model
    pretime = time.time()
    p = subprocess.run(['time', 'sby', '-f', 'sec.sby', 'taskBMC20_sodor5_model_lb_u'], cwd=test_dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    s = p.stdout.decode('utf-8')
    print(s)
    r_model = "DONE (PASS" in s
    posttime = time.time()
    model_time = posttime - pretime
    print(f"For test: {test} Model time: {model_time}")

    # Save the results
    os.system(f"cp -r {test_dir}/{mod_dir} {test_dir}/{test}")

    # Save the times
    times.append([
        test, test_description[i][0], test_description[i][1], dut_time, r_dut, model_time, r_model
    ])



with open("sodor5_sec_times.log", 'w') as f:
    f.write("// Generated by sodor5_security_script.py at {}\n\n\n".format(datetime.datetime.now()))

    table = tabulate.tabulate(times, headers=["Test", "Opcodes", "Secret inputs", "Design Runtime (s)", "Safe?", "Model Runtime (s)", "Safe?"])
    f.write(table)
