#!/usr/bin/env bash
# Run Argus locally (Chum to Json Server and Argus Frontend) and opens the browser
set -euo pipefail

WORKSPACE="$(bazel info workspace)"
TEMPFILE=""
SERVICE_PORT=""

build_chum_to_json_service() {
  echo "Building chum_to_json_service ..."
  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;
}

select_port() {
  for port in {9090..9109}; do
    if ! lsof -Pi ":$port" -sTCP:LISTEN -t > /dev/null; then
      SERVICE_PORT="$port"
      return 0
    fi
  done
  echo "Failed to find free port!"
  return 1
}

run_service() {
  echo "Starting chum_to_json_service ..."
  TEMPFILE="$(mktemp)"
  GLOG_minloglevel=0 bazel run --config=cuda --config=kraken //argus/chum_to_json_service:service_main -- \
    --port "$SERVICE_PORT" \
    --alsologtostderr \
    2>&1 | tee $TEMPFILE &
  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
}

run_frontend() {
  cd "$WORKSPACE/argus/frontend"
  yarn install
  CHUM_TO_JSON_SERVER="http://localhost:$SERVICE_PORT" yarn serve --open
}

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

trap cleanup EXIT
source $WORKSPACE/argus/frontend/setup.sh
build_chum_to_json_service
select_port
run_service
run_frontend
cleanup
