#!/usr/bin/env bash

# @see https://docs.acquia.com/pipelines/

# Only run on 3.x.x version of the module.
if [[ ! ${GIT_BRANCH} =~ ^3\.[0-9]{1,2}\.x$ ]]; then
  echo "${GIT_BRANCH} is not eligible for deployment"
  exit
fi

echo 'Download pipelines CLI tool...'
curl -o pipelines https://cloud.acquia.com/pipeline-client/download
chmod a+x pipelines
echo 'Configure credentials'
./pipelines configure --key=${api_key} --secret=${secret_key}

job_id=$(pipelines start --application-id $APP_ID --vcs-path ach-deployment-${GIT_BRANCH} --deploy-vcs-path ach-deployment-${GIT_BRANCH} -D ACH_VERSION=${GIT_BRANCH}-dev | grep -i 'job id' | awk '{print $3}')
echo "Deployment started with ID $job_id"

# Wait until the job is finished, 5 minutes maximum.
max_tries=20
tries=0
while [[ $(bc <<< "$max_tries > $tries") == 1 ]]; do
  p_status=$(pipelines status --job-id $job_id --application-id $APP_ID)
  in_progress=$(grep -i 'not finished' <<< $p_status)
  if [[ -z $in_progress ]]; then
    echo 'The job has been finished!'
    echo $p_status
    break
  fi
  printf "\rWaiting for job $job_id to finish..."
  sleep 15
  ((tries++))
done

failed=$(grep -i 'job failed' <<< $p_status)
if [[ -n $failed ]]; then
  exit 1
fi
