#!/usr/bin/env python3

import subprocess
import os

import shutil

ITERATIONS = 100
WORKDIR = "benchmark_workdir"
OVERWRITE_EXISTING = False

COMMITS = [
    ('6ac0d27', 7),
    ('1bbf978', 8),
    ('e31a477', 11),
    ('8093b18', 11),
    ('021b72b', 14),
    ('9a3ed05', 14),
    ('7244e11', 14),
    ('9de3efa', 14),
    ('2429bed', 14),
    ('2732d73', 14),
    ('f0adf9f', 14),
    ('f890895', 14),
    ('2d90970', 15),
    ('46097e7', 15),
    ('37a2f8b', 15)
]


def main():
    prev_size = None
    result_dir = os.path.join(os.getcwd(), "results")
    os.makedirs(result_dir, exist_ok=True)

    # setup workdir
    shutil.rmtree(WORKDIR, ignore_errors=True)
    subprocess.check_call(f"git clone $PWD {WORKDIR}", shell=True)
    os.chdir(WORKDIR)

    for (commit_hash, size) in COMMITS:
        print(f'{commit_hash}: {size}')
        checkout(commit_hash)
        compile()

        if prev_size != size and prev_size is not None:
            # Size changed so we measure with old and new
            bench(commit_hash, prev_size, result_dir)
        prev_size = size

        bench(commit_hash, size, result_dir)

    os.chdir("..")


def checkout(commit):
    subprocess.check_call(['git', 'checkout', commit])


def compile():
    subprocess.check_call(['make', 'clean'])
    subprocess.check_call(['make'])


def bench(commit_hash, size, result_dir, overwrite=OVERWRITE_EXISTING):
    file_name = os.path.join(result_dir, f'{commit_hash}_{size}.csv')
    if overwrite or not os.path.isfile(file_name):
        print("Benchmarking {} with size {}".format(commit_hash, size))
        with open(file_name, 'w') as f:
            for i in range(ITERATIONS):
                measure(f, size)


def measure(f, size):
    subprocess.check_call(
        f'perf stat ./nq {size} 2>&1 | grep "seconds" | awk \'{{print $1}}\'', shell=True, stdout=f)


if __name__ == '__main__':
    main()
