#!/bin/bash

CURRENT_VERSION=`git tag --sort=v:refname | tail -n 1`

echo -n "Version courante (avant merge) [$CURRENT_VERSION] > "
read TEMP
if [ "$TEMP" != "" ]; then
	CURRENT_VERSION=$TEMP
fi

CURRENT_VERSION=$(awk -F\v '{ print $2 }' <<< $CURRENT_VERSION)

MAJOR=$(echo $CURRENT_VERSION | cut -d "." -f 1)
MINOR=$(echo $CURRENT_VERSION | cut -d "." -f 2)
RELEASE=$(echo $CURRENT_VERSION | cut -d "." -f 3)

TEMP=""
until [ "$TEMP" == "a" ] || [ "$TEMP" == "m" ] || [ "$TEMP" == "r" ];
do
	echo -e "Upgrade : \n\tMajor\t[a]\n\tMinor\t[m]\n\tRelease\t[r]"
	echo -n "Choix [a|m|r] : "
	read TEMP
done

CHANGELOG_NAME=""

case $TEMP in
	"a")
		let MAJOR+=1
		MINOR=0
		RELEASE=0
		CHANGELOG_NAME="v"$MAJOR"."$MINOR
		;;
	"m")
		let MINOR+=1
		RELEASE=0
		CHANGELOG_NAME="v"$MAJOR"."$MINOR
		;;
	"r")
		let RELEASE+=1
		CHANGELOG_NAME="v"$MAJOR"."$MINOR"."$RELEASE
		;;
esac

VERSION="v"$MAJOR"."$MINOR"."$RELEASE

echo -n "Nouvelle version (après merge) : $VERSION - Continuer ? (o/N) > " 
read TEMP
if [ "$TEMP" != "o" ]; then
	exit 1
fi

BRANCH="$(git rev-parse --abbrev-ref HEAD)"

git checkout master

if [ "$(git rev-parse --abbrev-ref HEAD)" != "master" ]; then
	echo "Erreur de checkout vers master"
	exit 1
fi

if [ -f app/changelog/vcurrent.yml ]; then
	if [ -f app/changelog/$CHANGELOG_NAME.yml ]; then
		echo "Erreur: app/changelog/"$CHANGELOG_NAME".yml existe déjà!"
		echo "Fusionnez en manuel app/changelog/vcurrent.yml et app/changelog/"$CHANGELOG_NAME".yml puis supprimez app/changelog/vcurrent.yml"
		exit 1
	fi
	mv app/changelog/vcurrent.yml app/changelog/$CHANGELOG_NAME.yml
	git add app/changelog/$CHANGELOG_NAME.yml
	git commit app/changelog/ -m "Changelog"
fi

git checkout prod

if [ "$(git rev-parse --abbrev-ref HEAD)" != "prod" ]; then
	echo "Erreur de checkout vers prod"
	exit 1
fi

git reset --hard
git fetch
git pull

git merge master --no-ff -m "Mise en prod $VERSION"

git tag $VERSION

git push origin master prod
git push --tags

echo "Retour sur la branche $BRANCH"
git checkout $BRANCH

