#!/bin/bash

set -eo pipefail

P_SITE="$1"
P_ENV="$2"

if [[ -z "$P_SITE" ]]; then
  P_SITE="$TERMINUS_SITE"
fi
if [[ -z "$P_ENV" ]]; then
  P_ENV="$TERMINUS_ENV"
fi

if [[ -z "$P_SITE" ]] || [[ -z "$P_ENV" ]]; then
  echo "Provide a site and enviornment."
  exit 1
fi

echo "Starting environment deploy commands."
# Update the Drupal database
terminus -n drush "$P_SITE.$P_ENV" -- updatedb -y

# Clear Drupal cache
echo "Clearing Drupal cache."
terminus -n drush "$P_SITE.$P_ENV" -- cr

# If exported configuration is available, then import it.
if [[ "$SYNC_CONFIG" != "NO" ]]; then
  if [ -f "./.circleci/scripts/drush-config-import" ]; then
    ./.circleci/scripts/drush-config-import $P_SITE $P_ENV
  else
    "$( dirname $0 )/drush-config-import" $P_SITE $P_ENV
  fi
else
  echo "SYNC_CONFIG is set to 'NO'. Leaving configuration alone."
fi

echo "Clearing the Edge cache."
# Clear the environment cache
terminus -n env:clear-cache "$P_SITE.$P_ENV"

if [[ "$P_ENV" != 'live' ]] && [[ "$P_ENV" != 'test' ]]; then
  # Ensure secrets are set
  terminus -n secrets:set "$P_SITE.$P_ENV" token "$GITHUB_TOKEN" --file='github-secrets.json' --clear --skip-if-empty
fi

# We make the assummption that this script is being run from the project root.
# Allow for post deployment hooks.
if [ -f "./.circleci/scripts/post-drush-commands" ]; then
  ./.circleci/scripts/post-drush-commands $P_SITE $P_ENV
fi
