#!/usr/bin/env bash

set -euo pipefail

CURRENT=$(cat VERSION)
IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT"

# Fetch labels from the most recent merged MR for this commit.
MR_LABELS=$(curl -s --header "PRIVATE-TOKEN: ${GITLAB_API_TOKEN}" \
  "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/repository/commits/${CI_COMMIT_SHA}/merge_requests" \
  | jq -r '.[0].labels[]' 2>/dev/null || true)

if echo "$MR_LABELS" | grep -q "version::major"; then
  MAJOR=$((MAJOR + 1))
  MINOR=0
  PATCH=0
elif echo "$MR_LABELS" | grep -q "version::minor"; then
  MINOR=$((MINOR + 1))
  PATCH=0
else
  PATCH=$((PATCH + 1))
fi

NEW_VERSION="${MAJOR}.${MINOR}.${PATCH}"
echo "$NEW_VERSION" > VERSION
echo "Version bump: $CURRENT -> $NEW_VERSION"

git-cliff -r . --config cliff.toml -u --tag "$NEW_VERSION" --prepend CHANGELOG.md

git config user.name "Cinc Releng"
git config user.email "maintainers@cinc.sh"

git add VERSION CHANGELOG.md
git commit -m "chore(release): ${NEW_VERSION} [skip ci]"
git tag "$NEW_VERSION"
git push "https://gitlab-ci-token:${GITLAB_PUSH_TOKEN}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git" HEAD:main --tags
