#!/usr/bin/env python3

import argparse
import os
import os.path
import subprocess
import tempfile

descr = """This script will update the session information of a test, and then
rerun the test. It will run the test twice, so it takes some time.  """

curdir = os.getcwd()


def parse_options():
    args = None
    parser = argparse.ArgumentParser(description=descr)
    parser.add_argument(
        "testnames",
        metavar="testnames",
        nargs="+",
        help="session of these tests will be updated",
    )
    parser.add_argument(
        "--rewrite", dest="rewrite", action="store_true", help="Use rewrite option "
    )
    args = parser.parse_args()
    return args


def replaytest(testname):
    testdir = os.path.join("tests", testname)
    if not os.path.exists(testdir):
        testdir = os.path.join("internal", testname)
    try:
        print("switching to", testdir)
        os.chdir(testdir)
        subprocess.run(["../../lib/python/replay.py"])
    finally:
        os.chdir(curdir)


def run_all_tests_again(args):
    print("running tests again")
    fd, tmpfile = tempfile.mkstemp()
    with os.fdopen(fd, "w") as f:
        for name in args.testnames:
            f.write(name + "\n")
    try:
        run_tests_cmd = [
            "./run-tests",
            "--disc",
            "large",
            "--diffs",
            "--testlist",
            tmpfile,
        ]
        if args.rewrite:
            run_tests_cmd.append("--rewrite")
        subprocess.run(run_tests_cmd)
    finally:
        os.remove(tmpfile)


def main():
    args = parse_options()
    for testname in args.testnames:
        replaytest(testname)
    run_all_tests_again(args)


main()
