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

#
# GovCMS configuration import.
#

LAGOON_ENVIRONMENT_TYPE=${LAGOON_ENVIRONMENT_TYPE:-production}
GOVCMS_DEPLOY_WORKFLOW_CONFIG=${GOVCMS_DEPLOY_WORKFLOW_CONFIG:-import}
CONFIG_DEFAULT_DIR=${CONFIG_DEFAULT_DIR:-/app/config/default}
CONFIG_DEV_DIR=${CONFIG_DEV_DIR:-/app/config/dev}
LAGOON_GIT_SAFE_BRANCH=${LAGOON_GIT_SAFE_BRANCH:-master}

echo "GovCMS Deploy :: Configuration import"

if [ "$GOVCMS_DEPLOY_WORKFLOW_CONFIG" != "import" ]; then
  echo "[skip]: Workflow is not set to import."
  exit 0
fi

if [[ "$LAGOON_GIT_SAFE_BRANCH" = internal-govcms-update* ]]; then
  echo "[skip]: Configuration cannot be imported on update branches."
  exit 0
fi

# Check that there are configuration files.
set +e
# shellcheck disable=SC2012
config_count=$(ls -1 "$CONFIG_DEFAULT_DIR"/*.yml 2>/dev/null | wc -l)
# shellcheck disable=SC2012
dev_config_count=$(ls -1 "$CONFIG_DEV_DIR"/*.yml 2>/dev/null | wc -l)
set -e

if [ "$config_count" -eq 0 ] && [ "$dev_config_count" -eq 0 ]; then
  # There are no configuration files to import.
  echo "[skip]: There is no configuration."
  exit 0
fi

if ! drush status --fields=bootstrap | grep -q "Successful"; then
  echo '[skip]: Site is not available.'
  exit 0
fi

if [ "$config_count" -gt 0 ]; then
  echo "[update]: Import site configuration."
  drush config:import -y sync
fi

if [ "$LAGOON_ENVIRONMENT_TYPE" != "production" ] && [ "$dev_config_count" -gt 0 ]; then
  echo "[update]: Import dev configuration partially."
  drush config:import -y --source="$CONFIG_DEV_DIR" --partial
fi

echo "[success]: Completed successfully."
