#!/bin/bash

# This script will setup the database and then start the rails application

set -e

: ${VELUM_PORT:=80}

setup_database() {
  set +e

  TIMEOUT=90
  COUNT=0
  RETRY=1

  # let the user know that the UI is about to start
  # https://bugzilla.suse.com/show_bug.cgi?id=1031682
  ruby bin/serve-init-page.rb -p $VELUM_PORT --request-timeout=$TIMEOUT --bind-address=0.0.0.0 --ssl-certificate /etc/pki/velum.crt --ssl-private-key /etc/pki/velum.key public/503_database_not_ready.html &
  export TEMPORARY_SERVER_PID=$!

  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
        ;;
      "DB_READY")
        echo "Database ready"
        bundle exec rake db:migrate
        # UI and database is ready, so we can kill the temporary server
        # https://bugzilla.suse.com/show_bug.cgi?id=1031682
        kill -9 $TEMPORARY_SERVER_PID
        break
        ;;
    esac
  done
  set -e
}

setup_database
bundle exec "puma -C config/puma.rb"
