#!/usr/bin/env bash

set -eu

[[ $# -ne 0 ]] && echo "Usage: $0" && exit 1
[[ $(git status --porcelain) ]] && echo "Commit your changes" && exit 1
[[ $(git log --branches --not --remotes) ]] && echo "Push your commits" && exit 1

curr_version() {
    local version="$(git describe --abbrev=0 --tags --exclude='*-rc*')" && [[ ${version} == v* ]] && version=${version:1}
    echo "${version}"
}

next_version() {
    local version=${1:?missing version} && [[ ${version} == v* ]] && version=${version:1}
    local parts=(${version//./ })
    [[ ${#parts[@]} -ne 3 ]] && echo "Invalid version" && exit 1
    case $2 in
    major) ((++parts[0])); parts[1]=0; parts[2]=0;;
    minor) ((++parts[1])); parts[2]=0;;
    patch) ((++parts[2]));;
    esac
    echo "${parts[0]}.${parts[1]}.${parts[2]}"
}

# sync git refs
git fetch --all --prune --tags --prune-tags --force --quiet

# save user's initial branch
curr_branch=$(git branch --show-current)

# checkout mainstream, aka current minor
git checkout master --quiet
git pull --ff-only --quiet

# check version
[[ $(git describe --tags --abbrev=0 --exact-match) ]] && echo "Commit already tagged" && exit 1

# set versions
curr_version="$(curr_version)"
next_version="$(next_version "${curr_version}" patch)"

# tag release
echo "Releasing ${curr_version} -> ${next_version}"
git tag "v${next_version}"

# push release
git push --tags

# restore user's initial branch
git checkout "${curr_branch}" --quiet
