#!/usr/bin/env python3
#
# (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 os
import sys
import argparse
import subprocess


# Command-line arguments
parser = argparse.ArgumentParser(
    prog='time-pforth-build',
    description='Time pForth building itself.',
)
parser.add_argument('-n', '--times', type=int, metavar='N', default=1,
                    help='repeat build N times [default %(default)s]')
args = parser.parse_args()

# Check required environment variables are set
assert os.getenv('srcdir') is not None
assert os.getenv('abs_top_srcdir') is not None
assert os.getenv('TIME_BINARY') is not None
assert os.getenv('MIT_BINARY') is not None

os.chdir(os.path.join(os.environ['srcdir'], 'specializer/pforth/src/mit'))
try:
    os.remove('pforth-new')
except FileNotFoundError:
    pass

# Build pForth the given number of times with given options
subprocess.check_call(os.environ['TIME_BINARY'].split() +
                      [os.path.join(os.environ['abs_top_srcdir'],
                                    'build-aux/repeat'),
                       str(args.times),
                       os.environ['MIT_BINARY']] +
                      os.getenv('MIT_OPTIONS', '').split() +
                      ['pforth', 'make.fs'])

# Check the result once (assume it built the same each time!)
subprocess.check_call(['cmp', 'pforth', 'pforth-new'])
