#!/bin/bash

# @license Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
# For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license

# This script triggers Travis that verifies whether projects that depend on CKEditor 5 build correctly.
#
# In order to integrate the action in a new repository, you need add a few secrets in the new repository.
#   - INTEGRATION_CI_ORGANIZATION - a name of the organization that keeps the repository where the build should be triggered
#   - INTEGRATION_CI_REPOSITORY - a name of the repository where the build should be triggered
#   - INTEGRATION_CI_TRAVIS_TOKEN - an authorization token generated by Travis CLI: `travis --pro token`

# We want to trigger the integration build when current build was triggered by push commit or API call.
if [[ $TRAVIS_EVENT_TYPE != "push" && $TRAVIS_EVENT_TYPE != "api" ]]
then
  exit 0
fi

# Trigger the integration build only when checking the main branch in the repository.
if [[ $TRAVIS_BRANCH != "master" ]]
then
  exit 0
fi

REPOSITORY="ckeditor/ckeditor5"
LAST_COMMIT=$( git rev-parse HEAD )

BUILD_MESSAGE="Repository: $REPOSITORY\n\nCommit: https://github.com/$REPOSITORY/commit/$LAST_COMMIT."
REQUEST_BODY="{\"request\": { \"branch\": \"master\", \"message\": \"$BUILD_MESSAGE\" } }"

curl -s -X POST \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "Travis-API-Version: 3" \
  -H "Authorization: token $INTEGRATION_CI_TRAVIS_TOKEN" \
  -d "$REQUEST_BODY" \
  "https://api.travis-ci.com/repo/$INTEGRATION_CI_ORGANIZATION%2F$INTEGRATION_CI_REPOSITORY/requests"
