#!/bin/sh
##
# Trigger CI to run e2e test
#

# Collect BE and FE test environment url.
# If it's a PR, programmatically determine the URL based on the autogenerated route rather then relying on $LAGOON_ROUTE.
# The reason is CMDB sometimes set develop LAGOON_ROUTE as a project-level variable.
PR_BRANCH_REGEX="pr-"
if [[ $(expr match "$LAGOON_GIT_SAFE_BRANCH" $PR_BRANCH_REGEX) != 0 ]]; then
  FE_URL=$(echo $LAGOON_AUTOGENERATED_ROUTES | grep -Eo '(https://app[^,]*)')
  BRANCH=$LAGOON_PR_HEAD_BRANCH
else
  FE_URL=$(echo $LAGOON_AUTOGENERATED_ROUTES | grep -Eo '(https://app[^,]*)')
  BRANCH=$LAGOON_GIT_BRANCH
fi

# Add basic auth credentials to the url if it's enabled.
if [ $BASIC_AUTH == '1' ]; then
  BE_URL=${CONTENT_API_SERVER/https:\/\//https:\/\/$CONTENT_API_AUTH_USER:$CONTENT_API_AUTH_PASS@}
  FE_URL=${FE_URL/https:\/\//https:\/\/$CONTENT_API_AUTH_USER:$CONTENT_API_AUTH_PASS@}
else
  BE_URL=$CONTENT_API_SERVER
fi

echo "Triggering end to end testing for $LAGOON_PROJECT..."

E2E_ESTUARY_URL="${E2E_ESTUARY_URL:-http://estuary.sdp-services:8080/v1/actions/trigger-e2e}"
E2E_ESTUARY_TOKEN_PATH="${E2E_ESTUARY_TOKEN_PATH:-/run/secrets/kubernetes.io/serviceaccount/token}"
# Trigger GitHub Action to run the e2e workflow via estuary
curl --location --request POST "$E2E_ESTUARY_URL" \
  --header "Authorization: Bearer $(cat $E2E_ESTUARY_TOKEN_PATH)" \
  --header "Content-Type: application/json" \
  --data-raw '{
    "owner": "dpc-sdp",
    "repo": "ripple",
    "workflow": "e2e.yml",
    "ref": "'"$BRANCH"'",
    "be_url": "'"$BE_URL"'",
    "fe_url": "'"$FE_URL"'",
    "project": "reference-sdp-vic-gov-au"
  }'
