#!/usr/bin/env python

import os
import sys
import subprocess
import shutil

CMAKE            = '@CMAKE_COMMAND@'
CMAKE_BUILD_TYPE = '@CMAKE_BUILD_TYPE@'
TMPDIR           = '@TMPDIR@'
SRCDIR           = '@SRCDIR@'
GFLAGS_DIR       = '@gflags_BINARY_DIR@'

if __name__ == "__main__":
  if len(sys.argv) != 4:
    sys.stderr.write(' '.join(['usage:', sys.argv[0], '<test_name> <srcdir> <expect_fail:0|1>\n']))
    sys.exit(1)
  test_name   = sys.argv[1]
  srcdir      = sys.argv[2]
  expect_fail = (sys.argv[3].lower() in ['true', 'yes', 'on', '1'])
  bindir      = os.path.join(TMPDIR, test_name)
  if TMPDIR == '':
    sys.stderr.write('Temporary directory not set!\n')
    sys.exit(1)
  # create build directory
  if os.path.isdir(bindir): shutil.rmtree(bindir)
  os.makedirs(bindir)
  # configure the build tree
  if subprocess.call([CMAKE, '-DCMAKE_BUILD_TYPE:STRING='+CMAKE_BUILD_TYPE,
                             '-Dgflags_DIR:PATH='+GFLAGS_DIR,
                             '-DTEST_NAME:STRING='+test_name, srcdir], cwd=bindir) != 0:
    sys.stderr.write('Failed to configure the build tree!\n')
    sys.exit(1)
  # build the test project
  exit_code = subprocess.call([CMAKE, '--build', bindir, '--config', CMAKE_BUILD_TYPE], cwd=bindir)
  if expect_fail == True:
    if exit_code == 0:
      sys.stderr.write('Build expected to fail, but it succeeded!\n')
      sys.exit(1)
    else:
      sys.stderr.write('Build failed as expected\n')
      exit_code = 0
  sys.exit(exit_code)