#!/usr/bin/env bash
set -e

# You can replace the python version to check
PYTHON=${PYTHON:-`which python`}
TMPFILE=tmp.py

[ -x "`which strace`" ] || (echo strace not found; exit 1)
[ -x "${PYTHON}" ] || (echo python not found; exit 1)

# Check that the strace has the option for fault injection on read
strace -e trace=read -e fault=read python -c exit 2>&1 | grep fault && (echo strace does not support fault injection; exit 1)

# Make a clean slate (since having the .pyc for example effects the results)
rm ${TMPFILE} 2> /dev/null || true
rm ${TMPFILE}c 2> /dev/null || true

# Make a script which exits with non 1 error level (to distinguish from an import error)
cat <<EOF >${TMPFILE}
import os
os._exit(5)
EOF

# This script should execute fine (note that -B is added so the bad .pyc won't be created)
${PYTHON} -B -c "import ${TMPFILE}" || [ $? -eq 5 ] || (echo Script failed too early...; exit 1)
# This should fail because it could not read the .py file, if the bug exists, a bad .pyc will be produced
strace -P ${TMPFILE} -e trace=read -e fault=read ${PYTHON} -c "import ${TMPFILE}" || [ $? -eq 1 ] || (echo Script failed too early...; exit 1)
# If the bug exists, this should fail since a bad .pyc was produced already
${PYTHON} -c "import ${TMPFILE}" || [ $? -eq 5 ] || (echo Bug exists an incorrect .pyc has been produced; exit 1)
echo Script finished successfully
