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

# Ensure lagoon environment is set with the least destructive default.
LAGOON_ENVIRONMENT_TYPE=${LAGOON_ENVIRONMENT_TYPE:-production}

# @todo This strategy will be injected from .env or .lagoon.env Currently set to replicate the existing process.
# Determine the config strategy `import` vs `retain`.
GOVCMS_DEPLOY_WORKFLOW_CONFIG=${GOVCMS_DEPLOY_WORKFLOW_CONFIG:-import}
# Determine the content strategy `import` vs `retain`.
GOVCMS_DEPLOY_WORKFLOW_CONTENT=${GOVCMS_DEPLOY_WORKFLOW_CONTENT:-retain}
# Space-separated list of Db replica hosts.
MARIADB_READREPLICA_HOSTS="${MARIADB_READREPLICA_HOSTS:-}"
# The location of the application directory.
APP="${APP:-/app}"

# Check for presence of config files.
set +e # Prevent script failure when assigning 0.
# shellcheck disable=SC2012,SC2086
config_count=$(ls -1 $APP/config/default/*.yml 2>/dev/null | wc -l | tr -d ' ')
# shellcheck disable=SC2012,SC2086
dev_config_count=$(ls -1 $APP/config/dev/*.yml 2>/dev/null | wc -l | tr -d ' ')
set -e

echo "Running govcms-deploy"
echo "Environment type: $LAGOON_ENVIRONMENT_TYPE"
echo "Config strategy:  $GOVCMS_DEPLOY_WORKFLOW_CONFIG"
echo "Content strategy: $GOVCMS_DEPLOY_WORKFLOW_CONTENT"
echo "There are ${config_count} config yaml files, and ${dev_config_count} dev yaml files."

# Ensure tmp folder always exists.
mkdir -p "$APP/web/sites/default/files/private/tmp"

drush core:status

# Database options to configure the remote to use the read replica when
# performing read operations.
dump_opts=""
read_replica_enabled () {
  if [[ -z "$MARIADB_READREPLICA_HOSTS" ]]; then
    return
  fi

  if tables=$(drush sqlq 'show tables;' --database=read 2> /dev/null) && [ -n "$tables" ]; then
    dump_opts="--database=read"
  fi
}

# Database updates, cache rebuild, optional config imports.
common_deploy () {

  if [[ "$LAGOON_ENVIRONMENT_TYPE" = "development" && "$GOVCMS_DEPLOY_WORKFLOW_CONTENT" = "import" ]]; then
    echo "Performing content import."
    # shellcheck disable=SC2086
    drush --alias-path=/app/drush/sites @govcms.prod sql:dump --gzip --extra-dump=--no-tablespaces --result-file=/tmp/sync.sql -y
    drush rsync --alias-path=/app/drush/sites @govcms.prod:/tmp/sync.sql.gz /tmp/ -y
    gunzip < /tmp/sync.sql.gz | drush sqlc
    rm /tmp/sync.sql.gz
  fi

  drush cache:rebuild
  drush updatedb -y

  # Base configuration import with development environment overrides.
  if [[ "$GOVCMS_DEPLOY_WORKFLOW_CONFIG" = "import" && "$config_count" -gt 0 ]]; then
    echo "Performing config import."
    drush config:import -y sync
    if [[ "$LAGOON_ENVIRONMENT_TYPE" != "production" && "$dev_config_count" -gt 0 ]]; then
      echo "Performing development config import on non-production site."
      drush config:import -y --partial --source=../config/dev
    fi
  fi

  if [[ "$LAGOON_ENVIRONMENT_TYPE" != "production" ]]; then
    echo "Enable stage_file_proxy in non-prod environments."
    drush pm:enable stage_file_proxy -y
  fi

}

read_replica_enabled

if [[ "$LAGOON_ENVIRONMENT_TYPE" = "production" ]]; then

  if drush status --fields=bootstrap | grep -q "Successful"; then
    echo "Making a database backup."
    # shellcheck disable=SC2086
    mkdir -p "$APP/web/sites/default/files/private/backups/" && drush sql:dump $dump_opts --gzip --extra-dump=--no-tablespaces --result-file="$APP/web/sites/default/files/private/backups/pre-deploy-dump.sql"
    common_deploy
  else
    echo "Drupal is not installed or not operational."
  fi

else

  if ! drush status --fields=bootstrap | grep -q "Successful"; then
    echo "Drupal is not installed or not operational."

    if [[ "$LAGOON_ENVIRONMENT_TYPE" = "local" ]]; then
      echo "Drupal is not installed locally, try ahoy install"
    else
      # In a non-functioning development site, import the database from production before running import.
      # Note, this would destroy data in a dev site that was just broken temporarily. Review?
      # shellcheck disable=SC2086
      drush --alias-path=/app/drush/sites @govcms.prod sql:dump --gzip --extra-dump=--no-tablespaces --result-file=/tmp/sync.sql -y
      drush rsync --alias-path=/app/drush/sites @govcms.prod:/tmp/sync.sql.gz /tmp/ -y
      gunzip < /tmp/sync.sql.gz | drush sqlc
      rm /tmp/sync.sql.gz
      common_deploy
    fi
  else
    common_deploy
  fi

fi

echo "Finished running govcms-deploy."
