#!/usr/bin/env bash

# Enable debug mode and just crash if there are any untested command
set -x
set -e

function mysql_up() {
  ${DOCKER_COMPOSE} up --detach mysql
  # Maybe instead of sleep have a mysql command that checks it
  sleep 30
}

function db_setup() {
  ${DOCKER_COMPOSE} run --rm -e RAILS_LOG_LEVEL=error system rake db:drop db:setup
}

function system_availability() {
  ${DOCKER_COMPOSE} up --detach system

  # retry counter
  counter=0

  # Wait for 90 seconds with 5 seconds sleep
  while test $counter -lt 18; do
    SYSTEM_SMOKE_ADDR=$(docker container port system-smoke 3000 | head -n 1)

    # here we do not want to crash hardly
    set +e
    curl -s -H "X-Forwarded-Proto: https" "${SYSTEM_SMOKE_ADDR}/check.txt" | grep -q ok
    ret=$?
    set -e

    if [ $ret -eq 0 ]; then
      docker exec system-smoke bash -c '[ $(cat public/packs/manifest.json | wc -l) -ge 1 ]'
      return $?
    fi

    # increase the retry counter
    counter=$((counter+1))
    sleep 5

  done
  return 1
}

function teardown() {
  ${DOCKER_COMPOSE} rm -v --stop --force
}

trap teardown EXIT

mysql_up
db_setup
system_availability
teardown
