#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
set -e
. $DIR/environment.sh
. $DIR/keys.sh

# if it's transitive, then it means we are publishing to public
if [[ "$(npx rollup-umd-scripts publish status)" = transitive ]]; then
  echo "Pipeline from GitLab to GitHub is not ready yet!"
  exit 0
fi

GL_TOKEN=$GL_TOKEN npx semantic-release

# Will trigger the doc build using the newly created tag
if [[ ! -f ~/release_version ]]; then
  exit 0
fi

RELEASE_VERSION=$(cat ~/release_version)

function declination () {
  initial_process_wd=$PWD
  echo "[Release] Declination scripts will run with version ${RELEASE_VERSION:-$PACKAGE_VERSION}"
  cd
  $DIR/../../../internals/declination/create "${RELEASE_VERSION:-$PACKAGE_VERSION}" "${CI_COMMIT_REF_NAME}" "${GL_TOKEN:-$GITLAB_TOKEN}" > /dev/null
  cd $initial_process_wd
}


function page () {
  # trigger the page build on the new released version
  JSON_RES=$(curl -f -sS -X POST -H "PRIVATE-TOKEN: ${GL_TOKEN:-$GITLAB_TOKEN}" -F description=ci-auto-created https://module.kopaxgroup.com/api/v4/projects/${CI_PROJECT_ID}/triggers)
  TRIGGER_TOKEN=$(echo $JSON_RES | jq -r '.token') && TRIGGER_ID=$(echo $JSON_RES | jq -r '.id')
  sleep 3s
  curl -f -o /dev/null -S -X POST -F token="${TRIGGER_TOKEN}" -F ref="v${RELEASE_VERSION}" -F "variables[NPM_TOKEN]=${NPM_TOKEN}" -F "variables[NPM_TOKEN_KOPAXGROUP]=${NPM_TOKEN_KOPAXGROUP}" https://module.kopaxgroup.com/api/v4/projects/${CI_PROJECT_ID}/trigger/pipeline
  curl -f -S -X DELETE -H "PRIVATE-TOKEN: ${GL_TOKEN:-$GITLAB_TOKEN}" "https://module.kopaxgroup.com/api/v4/projects/${CI_PROJECT_ID}/triggers/${TRIGGER_ID}"
}

if [[ @yeutech/rollup-umd = $(node -p "require('./package.json').name") || $DECLINATION ]]; then
  declination
fi

page

. $DIR/unset.sh
