#!/usr/bin/env bash
#
## Find the next semantic version using GitHub Flow

set -e
set -o pipefail

## Get last master tag
last_tag=$(git describe --first-parent --abbrev=0 master)
>&2 echo Last Tag: ${last_tag}

## Parse semantic version from last tag
last_version=( ${last_tag//-/ } )
last_mmp_ver=( ${last_version[0]//./ } )
last_maj_ver=${last_mmp_ver[0]}
last_min_ver=${last_mmp_ver[1]}
last_pat_ver=${last_mmp_ver[2]}

## Get counts of changes since last release
brk_count=$(git rev-list ${last_tag}..HEAD --grep='^...\*' --count)
fea_count=$(git rev-list ${last_tag}..HEAD --grep='^fea:' --count)
msc_count=$(($(git rev-list ${last_tag}..HEAD --grep='^...:' --count) - fea_count))
>&2 echo BRK: ${brk_count}
>&2 echo FEA: ${fea_count}
>&2 echo MSC: ${msc_count}

## Prepare variable for export
unset next_maj_ver
unset next_min_ver
unset next_pat_ver
unset NEXT_VERSION

## Find next version
if [[ "${brk_count}" -gt 0 ]]; then
    ## Increment major version if breaking changes detected
    next_maj_ver=$((last_maj_ver + 1))
    next_min_ver='0'
    next_pat_ver='0'
else
    next_maj_ver=${last_maj_ver}
    if [[ "${fea_count}" -gt 0 ]]; then
        ## Increment minor version
        next_min_ver=$((last_min_ver + 1))
        next_pat_ver='0'
    else
        next_min_ver=${last_min_ver}
        ## Always increment patch version if only patch or no change was introduced
        next_pat_ver=$((last_pat_ver + 1))
    fi
fi
NEXT_VERSION=${next_maj_ver}.${next_min_ver}.${next_pat_ver}

>&2 echo Next Tag: ${NEXT_VERSION}
echo ${NEXT_VERSION}
