#!/bin/bash
set -o errexit -o nounset -o pipefail

[ "${DEBUG:-false}" == true ] && set -x

check_database_connection() {
  echo "Attempting to connect to database ..."
  case "${DB_CONNECTION}" in
    mysql)
      prog="mysqladmin -h ${DB_HOST} -u ${DB_USERNAME} ${DB_PASSWORD:+-p$DB_PASSWORD} -P ${DB_PORT} status"
      ;;
    pgsql)
      prog="/usr/bin/pg_isready"
      prog="${prog} -h ${DB_HOST} -p ${DB_PORT} -U ${DB_USERNAME} -d ${DB_DATABASE} -t 1"
      ;;
  esac
  timeout=60
  while ! ${prog} >/dev/null 2>&1
  do
    timeout=$(( timeout - 1 ))
    if [[ "$timeout" -eq 0 ]]; then
      echo
      echo "Could not connect to database server! Aborting ..."
      exit 1
    fi
    echo -n "."
    sleep 1
  done
  echo "Connection establised"
}

checkdbinitmysql() {
    table=sessions
    if [[ "$(mysql -N -s -h "${DB_HOST}" -u "${DB_USERNAME}" "${DB_PASSWORD:+-p$DB_PASSWORD}" "${DB_DATABASE}" -P "${DB_PORT}" -e \
        "select count(*) from information_schema.tables where \
            table_schema='${DB_DATABASE}' and table_name='${table}';")" -eq 1 ]]; then
        echo "Table ${table} exists!"
    else
        echo "Table ${table} does not exist!"
    fi

}

checkdbinitpsql() {
    table=sessions
    export PGPASSWORD=${DB_PASSWORD}
    if [[ "$(psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USERNAME}" -d "${DB_DATABASE}" -c "SELECT to_regclass('${table}');" | grep -c "${table}")" -eq 1 ]]; then
        echo "Table ${table} exists!"
    else
        echo "Table ${table} does not exist!"
    fi

}

check_configured() {
  case "${DB_CONNECTION}" in
    mysql)
      checkdbinitmysql
      ;;
    pgsql)
      checkdbinitpsql
      ;;
  esac
}

initialize_system() {
  echo "Initializing app container ..."

  # remove empty lines
  [ -f /var/www/html/.env ] && sed '/^.*=""$/d'  -i /var/www/html/.env

  rm -rf bootstrap/cache/*
}

migrate_db() {
  force=""
  if [[ "${FORCE_MIGRATION:-false}" == true ]]; then
    force="--force"
  fi
  php artisan migrate ${force}
}

seed_db() {
  php artisan db:seed
}

start_system() {
  initialize_system
  check_database_connection
  check_configured

  if [[ "${APP_ENV}" != "production" ]]; then
    migrate_db
    #seed_db
  fi

  echo "Starting app ..."
  php artisan storage:link
  php artisan config:cache
}

start_system
