#!/bin/bash

### Release next version of {{meta.name}}.

read -p "Are you sure to release new version? [y/n]" -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
    exit 1
fi

HERE=$(cd "$(dirname $0)" && pwd)

PROJECT=$(cd "${HERE}/.." && pwd)

REPO_NAME=origin

echo
echo "### Release project: ${PROJECT}"

if [[ ! -z $(git status -s) ]]
then
    git status -s
    echo [ERROR] You have uncommited changes. Abort now...
    exit
fi

git fetch --all

echo
echo "### Increment version on master branch"

git fetch ${REPO_NAME} master
git checkout master
apeman task versionUp
git add .
git commit -m "Version up"
git push ${REPO_NAME} master

echo
echo "### Build on bundle branch..."

CWD=$(cd "${PROJECT}/.." && pwd)
BUNDLED=${CWD}/.$(basename "${PROJECT}").bundle

rm -rf ${BUNDLED}
cp -rf ${PROJECT} ${BUNDLED}

cd ${BUNDLED}

echo BUNDLED=${BUNDLED}

BUNDLE_BRANCH_NAME=bundle

if [ `git branch --list ${BUNDLE_BRANCH_NAME}` ]
then
    git branch -D ${BUNDLE_BRANCH_NAME}
fi


if [ `git branch --list -r ${REPO_NAME}/${BUNDLE_BRANCH_NAME}` ]
then
    git reset --hard HEAD
    git checkout --track -B ${BUNDLE_BRANCH_NAME} ${REPO_NAME}/${BUNDLE_BRANCH_NAME}
    git fetch ${REPO_NAME} ${BUNDLE_BRANCH_NAME}
    git merge -m "Version up" ${REPO_NAME}/${BUNDLE_BRANCH_NAME}
else
    git checkout -B ${BUNDLE_BRANCH_NAME}
fi

echo

git merge -m "Follow to master" --no-ff -X theirs ${REPO_NAME}/master

apeman task build,cutLinks,doc,unitTest,package

echo
echo "### Push to bundle branch..."
git add . -A
git commit -m "Version up" -a
git push ${REPO_NAME} -u ${BUNDLE_BRANCH_NAME}


echo
echo "### Pushing tag..."
apeman task tag

echo
echo "### Clean up..."
cd ${PROJECT}
git fetch --all
git checkout -f master
rm -rf ${BUNDLED}