#!/bin/bash

usage()
{
	printf "\nWelcome,"
	printf "\nThis script is used with the propouse of optimize the version generation in your project\n"

	printf "\nHow to Use:"
	printf "\n\nA first parameter:"
	printf "\nUse '-r' to close a release branch"
	printf "\nUse '-h' to close a hotfix branch"
	printf "\n\nAnd a second parameter:"
	printf "\nUse '--front' to close a frontend repository"
	printf "\nUse '--back' to close a backend repository"
	printf "\n"
}

invalid()
{
	printf "\n $1 Option or Argument is invalid.\n"
}

case $1 in
	-r)
		BRANCH="release"
		;;
	-h)
		BRANCH="hotfix"
		;;
	*)
        invalid $1;
        usage;
		;;
esac

case $2 in
    --back)
        REPO=back
        ;;
    --front)
        REPO=front
        ;;
	*)
        invalid $2;
        usage;
        exit 1
		;;
esac

# Senior CI Extensions
. senior-ci/common/senior-ci-extensions-helpers.sh

# Import release helpers
. senior-ci/common/release-helpers.sh

# Import notification helpers
. senior-ci/common/notification-helpers.sh

get_version_release_candidate

git checkout $BRANCH/$VERSION_HYPHEN
git reset --hard origin/$BRANCH/$VERSION_HYPHEN

call_extension "before_change_changelog"

update_changelog_date

delete_empty_info_changelog

call_extension "after_change_changelog"

git commit -a -m "[CI] Fechando versão $VERSION" -m "[auto release]"

echo "[CI] Realizando o merge do branch $BRANCH/$VERSION_HYPHEN para a master"
git checkout master
git reset --hard origin/master
MERGE_MESSAGE=$(echo $(git rev-parse $BRANCH/$VERSION_HYPHEN)$'\t\t'"branch '$BRANCH/$VERSION_HYPHEN'" | git fmt-merge-msg)
git merge $BRANCH/$VERSION_HYPHEN --no-ff -m "$MERGE_MESSAGE" -m "[auto release]" -X theirs --allow-unrelated-histories

echo "[CI] Criando a tag $VERSION_HYPHEN"
git tag --force --annotate $VERSION_HYPHEN -m "Liberação da versão $VERSION"

echo "[CI] Realizando o merge da tag $VERSION_HYPHEN para a develop"
git checkout develop
git reset --hard origin/develop
MERGE_MESSAGE=$(echo $(git rev-parse $VERSION_HYPHEN)$'\t\t'"tag '$VERSION_HYPHEN'" | git fmt-merge-msg)
git merge $VERSION_HYPHEN --no-ff -m "$MERGE_MESSAGE" -m "[auto release]" --allow-unrelated-histories

# Replace temp placeholder for no conflits
sed -i 's/{versionTemp}/{version}/' $CI_PROJECT_DIR/CHANGELOG.md
sed -i 's/{dateTemp}/{date}/' $CI_PROJECT_DIR/CHANGELOG.md

git commit -a -m "[CI] Update Changelog" -m "[auto release]"

echo "[CI] Merges concluídos. Excluindo branch $BRANCH/$VERSION_HYPHEN"
git branch -D $BRANCH/$VERSION_HYPHEN

push_branch_changes

git push --delete origin $BRANCH/$VERSION_HYPHEN
git push --all --follow-tags

echo "[CI] Processo de GitFlow concluído."

call_extension "after_release"

echo "[CI] Criação da versão $VERSION realizado com sucesso. Execute o job 'package' para publicar esta versão no AWS S3."

notify_release_teams_channel

exit
