#!/bin/bash
set -eux
git_toplevel="$(git rev-parse --show-toplevel)"
pyrc="${git_toplevel}/pyproject.toml"
pythonpath="${git_toplevel}/usr/lib/python3/dist-packages"
export PYTHONPATH="${pythonpath}${PYTHONPATH+":${PYTHONPATH}"}"

pytest=(python3 -m pytest -o 'python_files=tests/*.py')
black=(black --config="${pyrc}" --color --diff --check)
pylint=(pylint --rcfile="${pyrc}")
mypy=(mypy --config-file="${pyrc}")

py_lib_to_test_list=(
  'stdisplay'
  'sanitize_string'
  'strip_markup'
  'unicode_show'
  'strict_config_parser'
)

for py_lib_to_test in "${py_lib_to_test_list[@]}"; do
  cd "${pythonpath}/${py_lib_to_test}/"
  # Ideally, these variables should be ignored by the tests...
  NO_COLOR="" COLORTERM="" TERM="xterm-direct" "${pytest[@]}" "${@}"
  "${black[@]}" .
  #find . -type f -name "*.py" -print0 | xargs -0 "${pylint[@]}"
  "${pylint[@]}" .
  "${mypy[@]}" .
done

stdin_file_read_utils=(stcat stcatn)
stdin_implicit_read_utils=(sttee stsponge strip-markup unicode-show)
stdin_utils=("${stdin_file_read_utils[@]}" "${stdin_implicit_read_utils[@]}")
utils=(stprint stecho "${stdin_utils[@]}")
cd "${git_toplevel}/usr/bin"
"${black[@]}" -- "${utils[@]}"
"${pylint[@]}" -- "${utils[@]}"
for file in "${utils[@]}"; do
  "${mypy[@]}" -- "${file}"
done

for util in "${stdin_file_read_utils[@]}"; do
  ./"${util}" <&-
  ./"${util}" - <&-
done
for util in "${stdin_implicit_read_utils[@]}"; do
  ./"${util}" <&-
done

## sanitize-string needs special handling because it takes a mandatory output
## string length argument.
./sanitize-string -- nolimit <&-

if ! [ -d "${HOME}/trojan-source" ]; then
  printf "%s\n" "WARNING: Not running unicode-testscript, ${HOME}/trojan-source does not exist.
To get it:

cd ~
git clone git@github.com:nickboucher/trojan-source.git" >&2
  exit 1
fi

cd "${git_toplevel}"
./unicode-testscript
