#! /bin/bash
#Runs a dockerized geoserver for testing.
#
#Usage: docker.geoserver.sh <arg>
#
#   start:     starts the test geoserver
#   stop:      stops the geoserver
#   start-dev: starts the geoserver with the data dir mounted. Useful
#              when adding layers of other config changes
#
#This script will build the docker image and inserts the riskscape config into
#it.

GEOSERVER_IMAGE_NAME=riskscape-geoserver
GEOSERVER_CONTAINER_NAME=${RISKCAPE_GEOSERVER_CONTAINER_NAME:-riskscape-test-geoserver}

RISKSCAPE_NETWORK=${RISKSCAPE_DOCKER_NETWORK:-riskscape-test}
RISKSCAPE_HOME=`realpath $(dirname $0)/..`
GEOSERVER_ROOT="${RISKSCAPE_HOME}/home/geoserver"

#Delay to ensure geoserver is ready to work
function waitForGeoServer {
  timeout 2m \
  docker run --network ${RISKSCAPE_NETWORK} \
    -v ${RISKSCAPE_HOME}/bin:/opt/riskscape \
    --rm \
    ruby:2.6.5-alpine \
    /opt/riskscape/wait-for-geoserver
}

#First need to ensure the network exists
if ! docker network list | grep ${RISKSCAPE_NETWORK} > /dev/null ; then
  echo "Creating docker network"
  docker network create riskscape-test
fi

if [[ "$1" == "stop" ]] ; then
  echo "Stopping riskscape-test-geoserver"
  docker container stop "${GEOSERVER_CONTAINER_NAME}"
  exit
fi
# we use chmod recursive to ensure all the files/directies in ${GEOSERVER_ROOT}
# can be written by the other user. This is to allow the tomcat user in the container
# to write to these locations where they end up in the docker container.
# They go to /var/local/geoserver which is a docker volume so chmod/chown in the
# Dockerfile doesn't work.
chmod -R o+w ${GEOSERVER_ROOT}
docker build --pull ${RISKSCAPE_HOME} -f Dockerfile.geoserver --tag ${GEOSERVER_IMAGE_NAME}
if [[ "$1" == "start" ]] ; then
  docker run --name "${GEOSERVER_CONTAINER_NAME}" \
      --network-alias riskscape-test-geoserver \
      -d --network ${RISKSCAPE_NETWORK} \
      --rm \
      ${GEOSERVER_IMAGE_NAME}
  #Delay to ensure geoserver is ready to work
  waitForGeoServer
elif [[ "$1" == "start-dev" ]] ; then
  docker run --name "${GEOSERVER_CONTAINER_NAME}" \
      --network-alias riskscape-test-geoserver \
      -d -p 8080:8080 --network ${RISKSCAPE_NETWORK} \
      -v ${GEOSERVER_ROOT}:/var/local/geoserver \
      --rm \
      oscarfonts/geoserver
  #Delay to ensure geoserver is ready to work
  waitForGeoServer
fi
