#!/bin/bash

set -e

usage() {
  echo -e "usage:\t$0 DIRECTORY, e.g. $0 pica-mattermost"
  echo -e "\tDIRECTORY : name of the directory containing docker-compose.yml\n"
  echo "This script is a helper to launch a service : it will create all needed volumes for the service,"
  echo "pull the specified version of the image if any, and then launch docker-compose up -d."
  exit 1
}

if [[ $# -ne 1 ]]; then
  echo "ERROR : wrong number of arguments"
  usage
fi

if [[ ! -d "$1" ]]; then
  echo "ERROR : directory does not exist ($1)"
  usage
fi

# Go to the folder of the service which will be tested
cd "$1"

echo -e "Starting procedure for \033[31m$1\e[0m..."

echo -e "\n==== Pull Dockerfiles repository ===="
echo -e "Using branch \033[31m $(git rev-parse --abbrev-ref HEAD)\e[0m, is this correct ? [y/N]"
read ans

if [ $ans == "y" ]; then
  git pull
else
  echo "Aborting."
  exit 0
fi

echo -e "\n==== Pull new versions of images ===="
docker-compose pull

echo -e "\n==== Ensure named external volumes are created ===="
for v in $(docker-compose config --volumes); do
  docker volume create "$v"
done

echo -e "\n==== Lauch $1 ===="
docker-compose up -d

echo -e "\n==== Print logs (use Ctrl+C to stop) ===="
docker-compose logs -f
