#!/usr/bin/env bash
# Run PCP-CI Web app locally (Metrics Server and Frontend).
set -euo pipefail

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

build_metrics_server() {
  echo "Building metrics_server ..."
  bazel build --config=cuda --config=kraken //web_apps/pcp_ci/metrics_server:metrics_server &
  if ! wait $!; then
    echo "Failed to build metrics_server!"
    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 metrics_server ..."
  TEMPFILE="$(mktemp)"
  bazel run --config=cuda --config=kraken //web_apps/pcp_ci/metrics_server:metrics_server -- \
    --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 metrics_server!"
      return 1;
    fi
  done
  echo "Timed out waiting for metrics_server!"
  return 1
}

run_frontend() {
  cd "$WORKSPACE/web_apps/pcp_ci/frontend"
  yarn install
  PCP_CI_BACKEND="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/web_apps/pcp_ci/frontend/install_yarn.sh
build_metrics_server
select_port
run_service
run_frontend
cleanup
