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

APP_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORKSPACE="$(bazel info workspace)"
TEMPFILE=""
CHUM_TO_JSON_PORT="9090"

build_chum_to_json_service() {
  echo "Building chum_to_json_service ..."
  pushd $WORKSPACE
  bazel build --config=cuda --config=kraken //argus/chum_to_json_service:service_main &
  if ! wait $!; then
    echo "Failed to build chum_to_json_service!"
    return 1
  fi;
  popd
}

run_service() {
  echo "Starting chum_to_json_service ..."
  pushd $WORKSPACE
  TEMPFILE="$(mktemp)"
  bazel run --config=cuda --config=kraken //argus/chum_to_json_service:service_main -- \
    --port "$CHUM_TO_JSON_PORT" \
    --alsologtostderr \
    2>&1 | tee $TEMPFILE &
  popd
  SERVICE_PID=$(jobs -p)
  for i in {1..60}; do
    sleep 1
    if grep -q "Listening on http:" $TEMPFILE; then
      return 0;
    fi
    if ! ps -p $SERVICE_PID > /dev/null; then
      echo "Failed to start chum_to_json_service!"
      return 1;
    fi
  done
  echo "Timed out waiting for chum_to_json_service!"
  return 1
}

cleanup() {
  pushd $WORKSPACE
  if [ -f "$TEMPFILE" ]; then
    rm $TEMPFILE
  fi
  popd
  # kill child processes of this shell
  pkill -P $$
}

# build & run chum2json
trap cleanup EXIT
build_chum_to_json_service
run_service

# activate python virtualenv, run package
PS1=${PS1:-} source /tmp/sim_service/bin/activate
python -m sim_service

cleanup
