#!/bin/bash
#
# Cloud Hook: post-code-update
#
# The post-code-update hook runs in response to code commits.
# When you push commits to a Git branch, the post-code-update hooks runs for
# each environment that is currently running that branch.
# See ../README.md for details.
#
# Usage:
# post-code-update site target-env source-branch deployed-tag repo-url repo-type

# Parameters.
platform="$1"
env="$2"
source_branch="$3"
deployed_tag="$4"
repo_url="$5"
repo_type="$6"

# Alias is for platform and environment
alias=$platform.$env

# Domain based on environment.
domain="-$env-cenitex.morpht.net"

# Sites in this platform, space delimited.
# Add the name of the site to this list when new site added.
sites=(default)

# Process each site.
for site in "${sites[@]}"
do
  START=$(date +'%s')
  # Turn maintenance mode on.
  uri=$site$domain
  echo -e "### Maintenance mode ON for $site at uri: $uri"
  drush9 @$alias -l $uri sset system.maintenance_mode 1

  # Run db updates.
  drush9 @$alias -l $uri updatedb -y

  # Run entity updates.
  drush9 @$alias -l $uri entity-updates -y --strict=0

  # Rebuild caches.
  drush9 @$alias -l $uri cache-rebuild -y

  # Turn maintenance mode off.
  echo -e "\n# Maintenance mode OFF for $site at uri: $uri"
  drush9 @$alias -l $uri sset system.maintenance_mode 0

  # Report downtime.
  echo -e "\n# $site at uri: $uri was in maintenance mode for $(($(date +'%s') - $START)) seconds."
done
