#!/bin/bash

if [ -n "$(git diff-index HEAD)" ];
then
  echo "branch creation isn't allowed with working tree changes"
else
  BRANCH_CURRENT=$(git rev-parse --abbrev-ref HEAD)
  git fetch -q
  COMMIT_ID_BRANCH_CURRENT=$(git rev-parse $BRANCH_CURRENT)
  COMMIT_ID_REMOTE_BRANCH_CURRENT=$(git rev-parse origin/$BRANCH_CURRENT)
  if [ "$COMMIT_ID_BRANCH_CURRENT" != "$COMMIT_ID_REMOTE_BRANCH_CURRENT" ];
  then
    echo "branch creation isn't allowed with changes between $BRANCH_CURRENT and origin/$BRANCH_CURRENT"
  else
    TYPE={{ branch_type }}
    TICKET={{ branch_ticket }}

    BRANCH_NEXT=$TYPE/$TICKET

    VERSION_LAST=$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout)

    VERSION=$(echo $VERSION_LAST | cut -d '-' -f 1)
    VERSION_MAJOR=$(echo $VERSION_LAST | cut -d'.' -f 1)
    VERSION_MINOR=$(echo $VERSION_LAST | cut -d'.' -f 2)
    VERSION_BUGFIX=$(echo $VERSION_LAST | cut -d'.' -f 3)

    VERSION_NEXT="${VERSION}-${TICKET}-1-SNAPSHOT"

    git checkout -b $BRANCH_NEXT
    ./mvnw versions:set -DnewVersion=$VERSION_NEXT -DgenerateBackupPoms=false
    git commit -n -am  "created branch ${BRANCH_NEXT}"
    git checkout ${BRANCH_CURRENT}
    git merge -s ours -m "merge branch ${BRANCH_NEXT} into ${BRANCH_CURRENT} [skip ci]" $BRANCH_NEXT
    git checkout $BRANCH_NEXT

    git push -u origin $BRANCH_NEXT
    git push origin $BRANCH_CURRENT
  fi
fi
