#!/bin/bash

# This script will setup the database

set -e

setup_database() {
  set +e

  TIMEOUT=90
  COUNT=0
  RETRY=1

  while [ $RETRY -ne 0 ]; do
    case $(bundle exec rails r bin/check_db.rb | grep DB) in
      "DB_DOWN")
        if [ "$COUNT" -ge "$TIMEOUT" ]; then
          printf " [FAIL]\n"
          echo "Timeout reached, exiting with error"
          exit 1
        fi
        echo "Waiting for mariadb to be ready in 5 seconds"
        sleep 5
        COUNT=$((COUNT+5))
        ;;
      "DB_EMPTY"|"DB_MISSING")
        # create db, apply schema and seed
        echo "Initializing database"
        bundle exec rake db:create
        # Start: patch_schema file hack (Please, read patch_schema for more information)
        # SCHEMA envvar is used by `db:schema:load` to allow providing an alternative schema
        # location
        if [ -f /var/lib/velum/schema.rb ]; then
          export SCHEMA=/var/lib/velum/schema.rb
        fi
        # End: patch_schema file hack
        bundle exec rake db:schema:load
        if [ $? -ne 0 ]; then
            echo "Error at setup time"
            exit 1
        fi
        bundle exec rake db:migrate
        ;;
      "DB_READY")
        echo "Database ready"
        bundle exec rake db:migrate
        bundle exec rake db:seed
        break
        ;;
    esac
  done
  set -e
}

setup_pillar_seeds() {
  # Import pillar seeds
  bundle exec rake velum:import_pillar_seeds
}

setup_cpi() {
  # Check if Cloud Provider config exists
  CPI_CONFIG="/etc/caasp/cpi/openstack.conf"
  if [ -f "${CPI_CONFIG}" ]; then
    # Import Cloud Provider config
    bundle exec rake cpi:openstack["${CPI_CONFIG}"]
  fi
}

setup_database
setup_pillar_seeds
setup_cpi
