#!/usr/bin/env bash
if [ -z "$SWAGGERHUB_API_KEY" ]
then
  echo "SWAGGERHUB_API_KEY is required to execute this file. Check swaggerhub for user key or environment to get a key"
  exit 1
fi

function postVersion() {
  ver=$1
  host=https://api.swaggerhub.com/apis/Pluto.TV/$SERVICE_NAME
  url="$host?version=$ver&oas=3.0.0&isPrivate=true&force=true"
  curl -X POST -d @$SWAGGER_FILE -H "Content-Type: application/json" -H "Authorization: $SWAGGERHUB_API_KEY" $url
}
branch_version=$(echo "$GIT_BRANCH" | sed -e "s/refs\/heads\///" | sed -e "s/\//_/" | sed -e "s/(^\w\d_.-)/ /" | sed -e "s/\^/ /g" | sed 's/ *$//g')
postVersion $branch_version

# we expect on master and main to be a tagged release so post the version
if [ $branch_version == "master" ]; then
  postVersion $VERSION
elif [[ $branch_version = main* ]]; then
  postVersion $VERSION
fi

# set the default branch
if [ $branch_version == "master" ]; then
  data="{\"version\": \"master\" }"
  url="$host/settings/default"
  curl -X PUT -H "Content-Type: application/json" -H "Authorization: $SWAGGERHUB_API_KEY" --data "$data" $url
fi
