#!/usr/bin/env bash

set -euo pipefail

# Get GitLab API URL from project URL
GITLAB_API_URL="$(echo $CI_PROJECT_URL | cut -d'/' -f1,2,3)/api/v4"

# Query running pipelines for the same branch, 
# process + filter them,
# finally cancel them with another API call
curl -sS -H "PRIVATE-TOKEN: $GITLAB_API_TOKEN" "${GITLAB_API_URL}/projects/$CI_PROJECT_ID/pipelines?ref=${CI_COMMIT_REF_NAME//\//%2F}&status=running" | \
jq '.[] | .id' | \
tail -n +2 | \
xargs -n 1 -I {} \
curl -sS -H "PRIVATE-TOKEN: $GITLAB_API_TOKEN" -X POST "${GITLAB_API_URL}/projects/$CI_PROJECT_ID/pipelines/{}/cancel"