#!/usr/bin/env bash

# safety checks
if [[ $# -ne 1 ]]; then
    echo "usage: $0 <major|minor|patch>" >&2
    exit 1
fi

if [[ "$(git rev-parse --abbrev-ref HEAD)" != 'master' ]]; then
    echo "not on the master branch" >&2
    exit 1
fi

# get latest and check if clean
if [[ -n "$(git status --porcelain)" ]]; then
    echo "working directory is dirty" >&2
    exit 1
fi

# get the current verison from last git tag into array and
# inc the provided part
semver_expression='s/^v([0-9]+)\.([0-9]+)\.([0-9]+).*$/\1 \2 \3/'
version=( $(git describe --tags | sed -E -e "$semver_expression" ) )
case "$1" in
    major)  ((version[0]++))
            version[1]=0
            version[2]=0
            ;;
    minor)  ((version[1]++))
            version[2]=0
            ;;
    patch)  ((version[2]++))
            ;;
    *)      echo 'please provide a valid version in increment' >&2
            exit 1
            ;;
esac
new_version="v${version[0]}.${version[1]}.${version[2]}"

# update meson.build
meson rewrite kwargs set project / version "$new_version"

# write version header
cat > include/version.h  <<EOL
#ifndef SUNCLOCK_VERSION_H
#define SUNCLOCK_VERSION_H

#define SUNCLOCK_VERSION "$new_version"

#endif
EOL

# create and tag single commit with a change to the version file
git commit --all --file - <<EOL
bump to $new_version

generated by \`release\` script in project root
EOL

# tag and remind 😵
git tag "$new_version"
echo "commited and tagged"
echo "remember to push tags"
