#!/bin/sh

# USAGE: commitlint-gitlab-ci
# USAGE: commitlint-gitlab-ci -x @commitlint/config-conventional

lines=`git log --oneline | wc -l`

if [ $lines -eq "1" ]
then
    # This is the first commit in the repository (or it is a force push for the
    # repository). We have to use the only commit.
    if [ ! -n $COMMITLINK_GITLAB_CI_VERBOSE ]
    then
        echo "commitlint from first commit"
    fi

    git log --pretty=format:%s HEAD | npx @commitlint/cli
else
    if [ "${CI_BUILD_BEFORE_SHA}" = "0000000000000000000000000000000000000000" ]
    then
        if [ ! -n $COMMITLINK_GITLAB_CI_VERBOSE ]
        then
            echo "commitlint from HEAD^"
        fi

        npx @commitlint/cli "$@" -f HEAD^
    else
        br=`git branch -r --contains ${CI_BUILD_BEFORE_SHA}`

        if [ -n $br ]
        then
            if [ ! -n $COMMITLINK_GITLAB_CI_VERBOSE ]
            then
                echo "commitlint from HEAD^"
            fi

            npx @commitlint/cli "$@" -f HEAD^
        else
            if [ ! -n $COMMITLINK_GITLAB_CI_VERBOSE ]
            then
                echo "commitlint from ${CI_BUILD_BEFORE_SHA}"
            fi

            npx @commitlint/cli "$@" -f "${CI_BUILD_BEFORE_SHA}"
        fi
    fi
fi
