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

#
# GovCMS database backups.
#
# This will perform a database backup. It is intended to
# be run as a pre-rollout task or early in the execution
# flow.
#

LAGOON_ENVIRONMENT_TYPE=${LAGOON_ENVIRONMENT_TYPE:-production}
GOVCMS_BACKUP_DIR=${GOVCMS_BACKUP_DIR:-/app/web/sites/default/files/private/backups}
GOVCMS_SKIP_DATABASE_BACKUP=${GOVCMS_SKIP_DATABASE_BACKUP:-}

# 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 :: Backup database"

# Backup processes only happen on production.
if [ "$LAGOON_ENVIRONMENT_TYPE" != "production" ]; then
  echo "[skip]: Non-production environment."
  exit 0
fi

# Allow optional database backup bypass.
if [ -n "${GOVCMS_SKIP_DATABASE_BACKUP}" ]; then
  echo "[skip]: Skipping database backup."
  exit 0
fi

STATUS=$("$DRUSH" status --fields=bootstrap --format=json)
if [ "$(jq -r '.bootstrap' 2> /dev/null <<< "$STATUS")" != "Successful" ]; then
  echo "[fail]: Drupal is not installed or operational."
  exit 0 # Perhaps exit > 0 to fail the build?
fi

mkdir -p "$GOVCMS_BACKUP_DIR"
"$DRUSH" sql:dump --gzip --extra-dump=--no-tablespaces --result-file="$GOVCMS_BACKUP_DIR/pre-deploy-dump.sql"

echo "[info]: Backup saved to $GOVCMS_BACKUP_DIR/pre-deploy-dump.sql."

echo "[success]: Completed successfully."
