#!/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 simulates the first launch of a service : it will recreate all existing volumes for the service"
  echo "to be sure that it works independently of the former configuration, and then launch 'docker-compose up -d'."
  echo "This way, you can test your Dockerfile | docker-compose on the testing VM as if it was a brand new VM."
  echo -e "\nAlso, it will temporarily replace all occurences of 'picasoft.net' by 'test.picasoft.net' for convenience."
  echo -e "\nThis script will also use the image uploaded on the testing registry, not the production registry."
  echo -e "\nUSE THIS SCRIPT ONLY ON THE TESTING VM."
  exit 1
}

if [[ $(hostname) != *"test"* ]]; then
  echo "ERROR : DO NOT USE OUTSIDE OF A TEST MACHINE !"
  usage
fi

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..."

if [[ -d secrets ]]; then
  cd secrets
  echo -e "\n==== Create dumb secret files ===="
  for f in *.secrets.example; do
      echo -e "\tFile $1/secrets/$(basename -- "$f" .secrets.example).secrets created"
      cp -- "$f" "$(basename -- "$f" .secrets.example).secrets"
  done
  cd ..
fi

echo -e "\n==== Stop and remove existing containers ===="
docker-compose down

echo -e "\n==== RESET HARD and 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 reset --hard
  git pull
else
  echo "Aborting."
  exit 0
fi

echo -e "\n==== Replace production URL with testing URL in all files ===="
for f in $(grep -l -r ".picasoft.net" .); do
  echo -e "\tFound in" ${f}
  sed -i "s/.picasoft.net/.test.picasoft.net/g" ${f}
done

echo -e "\n==== Remove and re-create named external volumes ===="
for v in $(docker-compose config --volumes); do
  # Don't fail if volume does not exists
  docker volume rm "$v" || true
  docker volume create "$v"
done

echo -e "\n==== Remove old images ===="
# For some reasons, sometime docker-compose does not pull the newer image. Force this!
docker-compose config | grep "image:" | cut -d ':' -f 2- | xargs docker image rm || true

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

echo -e "\n==== Lauch $1 and restore repository ===="
docker-compose up -d
git reset --hard

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