#!/usr/bin/env python3

import os
import sys
import shutil
import random
import subprocess

def bench(algo_dir, template_dir="templates/linux"):
    print(algo_dir)
    build_dir = None
    while build_dir is None:
        r = "%09d" % random.randint(0, 999999999)
        d = os.path.join("build", r)
        if not os.path.isdir(d):
            build_dir = d
    
    shutil.copytree(algo_dir, build_dir)

    c = os.path.join(build_dir, "genkat_aead.c")
    if os.path.exists(c):
        os.remove(c)

    hfiles = []
    cfiles = []
    for r, d, f in os.walk(build_dir):
        for file in f:
            if file.endswith(".c"):
                cfiles.append(file)
            elif file.endswith(".h"):
                hfiles.append(file)

    for f in os.listdir(template_dir):
        dst = os.path.join(build_dir, f)
        src = os.path.join(template_dir, f)
        if os.path.isfile(src) or os.path.islink(src):
            shutil.copy2(src, dst)
        elif os.path.isdir(src):
            shutil.copytree(src, dst)
        else:
            raise Exception("I don't know what %s is" % src)

    wd = os.getcwd()
    try:
        env = os.environ

        env['SRC_FILES'] = ' '.join(cfiles)
        env['HDR_FILES'] = ' '.join(hfiles)

        os.chdir(build_dir)
        if os.path.isfile('./configure'):
            p = subprocess.Popen(["./configure"], env=env)
            compout, comperr = p.communicate()
            print(compout)
            print("---")
            print(comperr)

        pargs = ['make']
        p = subprocess.Popen(pargs, env=env)
        compout, comperr = p.communicate()
        print(compout)
        print("---")
        print(comperr)

    finally:
        os.chdir(wd)
        # shutil.rmtree(build_dir)

    exit(0)  # stop immediately for now



def main(argv):
    submissions_dir = "all-lwc-submission-files"
    template_dir = "templates/linux"
    if len(argv) > 1:
        template_dir = argv[1]
    print("Using template %s" % template_dir)
    subs = os.listdir(submissions_dir)

    files = set()
    for submission in subs:
        implementations_dir = os.path.join(submissions_dir, submission, "Implementations", "crypto_aead")

        # r=root, d=directories, f = files
        for r, d, f in os.walk(implementations_dir):
            for file in f:
                if file == "encrypt.c":
                    f = os.path.join(r, file)
                    d = os.path.split(f)[0]
                    bench(d, template_dir)
                    assert os.path.isdir(d)
                    files.add(d)
        print()


if __name__ == "__main__":
    sys.exit(main(sys.argv))
