#!/bin/bash
#
# This kicks off a pipeline in the riskscape/eqc and riskscape/niwa-tests projects
# for either a git reference of the same name as this one or "master" if none exists.
#
# In general, this will only ever run for the 'master' branch. Currently
# .gitlab-ci.yml won't run this for private branches.
#
# It expects to run within a CI environment, and will probably blow up
# otherwise. In addition to the default set of variables provided by
# GitLab, this script needs the following:
#
#  - RISKSCAPE_WEB_UI_PROJECT_ID (set to the project ID)
#  - RISKSCAPE_EQC_PROJECT_ID (set to the project ID)
#  - RISKSCAPE_NIWA_PROJECT_ID (set to the project ID)
#  - CI_JOB_TOKEN (an access token with API access rights)
#

trigger_gitlab_pipeline () {
  BRANCH_NAME=${1}
  GITLAB_PROJECT_ID=${2}
  curl -fs -X POST -F ref="${BRANCH_NAME}" -F token="${CI_JOB_TOKEN}" "${CI_API_V4_URL}/projects/${GITLAB_PROJECT_ID}/trigger/pipeline"
}

display_pipeline_result() {
  BRANCH_NAME=${1}
  JSON_OUTOUT=${2}
  echo "Triggered downstream build for the '$BRANCH_NAME' branch:"

  # jq is simpler to parse the JSON, but might not be installed on the runner
  if [ -n "$(which jq)" ] ; then
    echo $JSON_OUTOUT | jq -r .web_url
  else
    # poor man's alternative: grep the relevant URL out of the JSON
    VALID_URL_CHARS="[0-9a-zA-Z\-/.:]"
    echo $JSON_OUTOUT | grep -Po "https://${VALID_URL_CHARS}*/riskscape/${VALID_URL_CHARS}*"
  fi
}

if test -z "$CI_JOB_TOKEN"
then
  echo "No CI Job token, skipping downstream builds."
  exit 1
fi

trigger_downstream_build () {
  PROJECT_ID=${1}
  if pipeline=$(trigger_gitlab_pipeline "${CI_COMMIT_REF_NAME}" ${PROJECT_ID})
  then
    display_pipeline_result "${CI_COMMIT_REF_NAME}" "$pipeline"
  elif test $? -eq 22 && pipeline=$(trigger_gitlab_pipeline master ${PROJECT_ID})
  then
    # this case gets hit for tagged release builds, as CI_COMMIT_REF_NAME will be the VERSION ID
    display_pipeline_result master "$pipeline"
  else
    echo "Unable to trigger build for either ${CI_COMMIT_REF_NAME} or master!"
    exit 1
  fi
}

echo "Triggering CI pipeline for riskscape-platform..."
trigger_downstream_build ${RISKSCAPE_PLATFORM_PROJECT_ID}

echo "Triggering CI pipeline for EQC..."
trigger_downstream_build ${RISKSCAPE_EQC_PROJECT_ID}

echo "Triggering CI pipeline for NIWA..."
trigger_downstream_build ${RISKSCAPE_NIWA_PROJECT_ID}
