#!/usr/bin/env bash
set -eo pipefail

# default variables
: "${PORT:=8000}"
: "${SLEEP:=1}"
: "${THREADS:=8}"
: "${TRIES:=60}"
: "${WORKERS:=4}"

usage() {
  echo "usage: bin/run web|web-dev|test|python|shell"
  exit 1
}

wait_for() {
  tries=0
  echo "Waiting for $1 to listen on $2..."
  while true; do
    [[ $tries -lt $TRIES ]] || return
    (echo > /dev/tcp/$1/$2) >/dev/null 2>&1
    result=
    [[ $? -eq 0 ]] && return
    sleep $SLEEP
    tries=$((tries + 1))
  done
}

[ $# -lt 1 ] && usage

case $1 in
  web)
    . /opt/conda/etc/profile.d/conda.sh && conda activate taar-37 && exec newrelic-admin run-program gunicorn taar.flask_app:app --bind 0.0.0.0:${PORT} --workers ${WORKERS} --threads ${THREADS} --access-logfile -
    ;;
  web-dev)
    exec python taar/flask_app.py --host=0.0.0.0 --port=${PORT}
    ;;
  test)
    . /opt/conda/etc/profile.d/conda.sh && \
        conda activate taar-37 && \
        rm -f coverage.xml &&\
        coverage erase && \
        pytest --cov && \
        # submit coverage
        coverage xml
        bash <(curl -s https://codecov.io/bash)
    ;;
  python)
    shift
    . /opt/conda/etc/profile.d/conda.sh && conda activate taar-37 && exec python $@
    ;;
  shell)
    shift
    . /opt/conda/etc/profile.d/conda.sh && conda activate taar-37 && exec bash $@
    ;;
  *)
    exec "$@"
    ;;
esac
