#!/usr/bin/env python3
# Run a brainfuck test.
#
# (c) Mit authors 2019-2020
#
# The package is distributed under the MIT/X11 License.
#
# THIS PROGRAM IS PROVIDED AS IS, WITH NO WARRANTY. USE IS AT THE USER’S
# RISK.

import io
import os
import sys
import subprocess

from mit.state import State

from redirect_stdout import stdout_redirector


if len(sys.argv) != 2:
    print("Usage: run-brainfuck-test BRAINFUCK-FILE", file=sys.stderr)
    sys.exit(1)
brainfuck_file = sys.argv[1]

object_file = os.path.splitext(os.path.basename(brainfuck_file))[0] + ".obj"
with open(brainfuck_file, 'rb') as f:
    returncode = subprocess.run(
        [os.environ['PYTHON'], os.path.join(os.environ['srcdir'], 'brainfuck'), object_file],
        input=f.read(),
    ).returncode
    if returncode == 2:
        sys.exit(77) # Program does not fit in Mit's memory; signal test skip
    elif returncode != 0:
        raise
VM = State()
VM.load(object_file)
VM.dump(VM.M.start)
VM.disassemble(VM.M.start, 64)
f = io.BytesIO()
with stdout_redirector(f):
    VM.run()
output = f.getvalue()
correct_file = os.path.splitext(brainfuck_file)[0] + ".correct"
correct = open(correct_file, "rb").read()
os.remove(object_file)

print(f"Output:\n{output}\n\nCorrect:\n{correct}")
assert(output == correct)
