#! /bin/bash
#Runs a dockerized postgis for testing.
#
#Usage: docker.postgis.sh <arg>
#
#   start:     starts the test postgis
#   stop:      stops the postgis
#
#This script will build the docker image and inserts the riskscape config into
#it.

POSTGIS_IMAGE_NAME=riskscape-postgis
POSTGIS_CONTAINER_NAME=${RISKCAPE_POSTGIS_CONTAINER_NAME:-riskscape-postgis}
POSTGIS_PUBLISH_PORT=${POSTGIS_PUBLISH_PORT:-55432}

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

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

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

if [[ "$1" == "stop" ]] ; then
  echo "Stopping ${POSTGIS_CONTAINER_NAME}"
  docker container stop "${POSTGIS_CONTAINER_NAME}"
elif [[ "$1" == "start" ]] ; then
  docker build --pull ${RISKSCAPE_HOME}/docker/postgis -f ${RISKSCAPE_HOME}/docker/postgis/Dockerfile --tag "${POSTGIS_IMAGE_NAME}"
  docker run --name "${POSTGIS_CONTAINER_NAME}" \
      --network-alias riskscape-postgis \
      --publish ${POSTGIS_PUBLISH_PORT}:5432 \
      -d --network "${RISKSCAPE_NETWORK}" \
      --rm \
      "${POSTGIS_IMAGE_NAME}"
  waitForPostGis
fi
