#!/usr/bin/env bash
IFS=$'\n\t'
set -euo pipefail

#
# GovCMS update database.
#

LAGOON_ENVIRONMENT_TYPE=${LAGOON_ENVIRONMENT_TYPE:-production}
GOVCMS_DEPLOY_UPDB=${GOVCMS_DEPLOY_UPDB:-true}
GOVCMS_DEPLOY_PRE_UPDB=${GOVCMS_DEPLOY_PRE_UPDB:-false}
GOVCMS_CACHE_REBUILD_PRE_UPDB=${GOVCMS_CACHE_REBUILD_PRE_UPDB:-true}

# Drush 12 support.
DRUSH="${GOVCMS_DRUSH:-none}"
if [ "$DRUSH" == "none" ]; then
  DRUSH=$(which /app/vendor/bin/drush > /dev/null 2>&1 && echo "/app/vendor/bin/drush" || echo "/usr/local/bin/drush")
fi

echo "GovCMS Deploy :: Update Database"

if [ "$GOVCMS_DEPLOY_UPDB" != "true" ]; then
  # Skip the database updates for this deploy.
  echo "[skip]: Environment variable is set to skip."
  exit 0
fi

if [ "$GOVCMS_DEPLOY_PRE_UPDB" != "false" ]; then
  # If we have the pre_updb task configured for this deployment
  # then we don't need to re-run the databases updates.
  echo "[skip]: Pre-deploy updates were applied."
  exit 0
fi

STATUS=$("$DRUSH" status --fields=bootstrap --format=json)
if [ "$(jq -r '.bootstrap' 2> /dev/null <<< "$STATUS")" != "Successful" ]; then
  echo '[skip]: Site is not available.'
  exit 0
fi

"$DRUSH" eval "\Drupal::service('extension.list.theme')->reset()->getList();"
if [ "$GOVCMS_CACHE_REBUILD_PRE_UPDB" != "false" ]; then
  # Allow forced cache-rebuild prior to database updates.
  echo "[info]: Rebuilding cache before database updates."
  "$DRUSH" cr
fi

echo "[info]: Preparing database update."
"$DRUSH" updatedb -y

echo "[success]: Completed successfully."
