#!/usr/bin/env bash
#
## Find the next semantic version using CLiO Flow on standalone applications

set -e
set -o pipefail

## Ensure current branch is master
current_branch=$(git rev-parse --abbrev-ref HEAD)
if [[ "${current_branch}" != 'master' ]]; then
  >&2 echo "On ${current_branch} instead of master. Exiting...."
  exit 1
fi

## 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}
    if [[ "${msc_count}" -gt 0 ]]; then
      ## Increment patch version
      next_pat_ver=$((last_pat_ver + 1))
    else
      next_pat_ver=${last_pat_ver}
    fi
  fi
fi
NEXT_VERSION=${next_maj_ver}.${next_min_ver}.${next_pat_ver}

if [[ ${NEXT_VERSION} = ${last_version[0]} ]]; then
  >&2 echo 'Version bump is unnecessary.'
  exit 1
fi

echo ${NEXT_VERSION}
