#!/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

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

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

DRY_RUN=${DRY_RUN:-}
if [ -n "$DRY_RUN" ]; then URL="$URL?dryrun=$DRY_RUN"; URL_V2="$URL_V2?dryrun=$DRY_RUN"; echo "use dry run"; fi

# 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 --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
}

mkdir -p /tmp/$YAML_DIR
cat $ROOT/$YAML_DIR/tiers*.yaml > /tmp/$YAML_DIR/tiers.yaml
cat $ROOT/$YAML_DIR/tier_unit*.yaml > /tmp/$YAML_DIR/tier_units.yaml
cat $ROOT/$YAML_DIR/sku*.yaml > /tmp/$YAML_DIR/tier_skus.yaml

echo "start calling central API..."

echo "call v2 API..."
curlf $URL_V2 -H "authorization: $AUTHORIZATION" -F tiers.yaml="@/tmp/$YAML_DIR/tiers.yaml" -F tier_units.yaml="@/tmp/$YAML_DIR/tier_units.yaml" -F skus.yaml="@/tmp/$YAML_DIR/tier_skus.yaml" -F commitId="$COMMIT_ID"
echo ""
echo "call v2 API SUCCESS"

echo "success call central API"
