import os
import sys
import subprocess


# <<<  grab current environment  >>>
lenv = os.environ.copy()

# <<<  inspect psi_scratch  >>>
psans = os.getenv('PSI_SCRATCH', None)
if psans is not None and os.access(psans, os.W_OK | os.X_OK):
    pass  # all good, can use user's env
else:
    lenv['PSI_SCRATCH'] = '/tmp'

# <<<  print test input  >>>
with open('run_test.in', 'w') as handle:
    handle.write("""
memory 250 mb

molecule h2o {
  O
  H 1 0.96
  H 1 0.96 2 104.5
}

set basis cc-pVDZ
energy('scf')

compare_values(-76.02663273, get_variable('SCF TOTAL ENERGY'), 6, 'SCF energy')
""")

# <<<  test the environment  >>>
sp = subprocess.Popen("""{}/bin/psi4 run_test.in""".format(os.environ['PREFIX']),
    shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=lenv)
out, err = sp.communicate()
if out:
    print(out)
if err:
    print(err)

# <<<  trigger conda build to fail if test case failed  >>>
sys.exit(sp.returncode)
