#!/bin/bash

set -eo pipefail

function finish() {
  # Check if LATEST_DOCKER was set
  echo Attempting to kill "$LATEST_DOCKER"
  docker kill $LATEST_DOCKER

  # Return to original working directory
  cd $ORIGINAL_WD
}

# Trap on any exit
trap finish EXIT SIGINT SIGTERM

ORIGINAL_WD=`pwd`

# get the location of this script https://stackoverflow.com/a/246128
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

cd $DIR/frontend

# Retrieve and add the mapbox API token to a .env.local file
echo VUE_APP_MAPBOX_TOKEN=$(vault read -field=token secret/map_box) > .env.local

# build frontend
docker build -t clams_console .
# Get PID of clams_console job
docker run -it -d -p 8080:8080 -v `pwd`:/workspace clams_console:latest ./build_app.sh
# Get the name of the latest docker instance
LATEST_DOCKER=$(docker ps -l --format "{{.Names}}")

# start backend
bazel-run.sh //mapping/clams_console:clams_console
