#!/bin/bash

version_regex='^release/([0-9]+)\.([0-9]+)\.(([0-9]*)((a|b|rc)([0-9]*))?)\.?[0-9]*'
git_string=${GERRIT_REFNAME:10}

if [[ $git_string =~ $version_regex ]]; then
    major_version="${BASH_REMATCH[1]}"
    minor_version="${BASH_REMATCH[2]}"
    patch_version="${BASH_REMATCH[3]}"
    pre_release="${BASH_REMATCH[6]}"
    pre_release_version="${BASH_REMATCH[5]}"
    commits_ahead="${BASH_REMATCH[8]}"
    commit_hash=$(git log --pretty=format:'%h' -n 1)
    echo "Major: $major_version"
    echo "Minor: $minor_version"
    echo "Patch: $patch_version"
    echo "Pre release: $pre_release"
    echo "Pre release version: $pre_release_version"
    echo "Commits ahead: $commits_ahead"
    echo "Commit hash: $commit_hash"

    echo "${BASH_REMATCH[*]}"
else
    echo "Error: git describe did not output a valid version string. Valid Git Tags are: release/1.0.42a1 release/1.0.42b1 release/1.0.42rc1 release/1.0.42 Unable to update VERSION file" >&2
    exit 1
fi

version_num="${major_version}.${minor_version}.${patch_version}"
dev_version_num="${major_version}.${minor_version}.${patch_version}.${commits_ahead}"
full_version_num="${version_num}.${commits_ahead}-${commit_hash}"

# Working directory of a git hook is always the root of the repo
cat > $(pwd)/VERSION <<EOM
MAJOR=$major_version
MINOR=$minor_version
PATCH=$patch_version
COMMITS_AHEAD=$commits_ahead
COMMIT_HASH=$commit_hash
VERSION_NUM=$version_num
DEV_VERSION_NUM=$dev_version_num
FULL_VERSION_NUM=$full_version_num
EOM

cat $(pwd)/lib/setup.py | sed "/version=/ s/=.*/='${version_num}',/" > $(pwd)/lib/setup.new
mv $(pwd)/lib/setup.new $(pwd)/lib/setup.py

cat $(pwd)/lib/fischertechnik/__init__.py | sed "/__version__ =/ s/= .*/= '${version_num}'/" > $(pwd)/lib/fischertechnik/__init__.new
mv $(pwd)/lib/fischertechnik/__init__.new $(pwd)/lib/fischertechnik/__init__.py

if [[ -z "$pre_release" ]]; then
	echo "Commit main release to stable branch with jenkins user"
	git add $(pwd)/lib/setup.py $(pwd)/lib/fischertechnik/__init__.py $(pwd)/VERSION
	git commit -am "release $version_num"
	git push --force origin HEAD:stable
fi
