#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail

ROOT=$(dirname "${BASH_SOURCE[0]}")/..

which curl || false

AUTHORIZATION=${AUTHORIZATION:-}
if [ -z "$AUTHORIZATION"  ]; then echo "AUTHORIZATION is blank"; exit 1; fi

case ${ENVIRONMENT:-""} in
    local)
        URL_V2="http://localhost:11000/external-api/v1/orgs/profile/sync_infra_profile"
        ;;
    dev)
        URL_V2="https://us-west-2.nightly.shared.aws.tidbcloud.com/external-api/v1/orgs/profile/sync_infra_profile"
        ;;
    staging)
        URL_V2="https://us-west-2.staging.shared.aws.tidbcloud.com/external-api/v1/orgs/profile/sync_infra_profile"
        ;;
    prod)
        URL_V2="https://us-west-2.prod.aws.tidbcloud.com/external-api/v1/orgs/profile/sync_infra_profile"
        ;;
    *)
        echo "ENVIRONMENT must be one of local, dev, staging, prod"
        exit 1
        ;;
esac

# make cURL fail with an exitCode different than 0 if the HTTP status code is not 200
# ref https://superuser.com/a/1641410/1649175
# --fail-with-body need curl v7.76 or newer
curlf() {
  OUTPUT_FILE=$(mktemp)
  HTTP_CODE=$(curl -X POST --silent --output $OUTPUT_FILE --write-out "%{http_code}" "$@")
  if [[ ${HTTP_CODE} -lt 200 || ${HTTP_CODE} -gt 299 ]] ; then
    >&2 cat $OUTPUT_FILE
    return 22
  fi
  cat $OUTPUT_FILE
  rm $OUTPUT_FILE
}


echo "start calling central API..."

echo "call v2 API..."
curlf $URL_V2 -H "authorization: $AUTHORIZATION"
echo ""
echo "call v2 API SUCCESS"

echo "success call central API"
