#!/usr/bin/env bash
#
# 1. Performs a release. This is a git operation to be performed by a human.
#    This release script will:
#
#   a. Check everything is committed (no untracked or uncommitted file(s)
#      otherwise the release process is aborted)
#   b. Bump the current version according to the release level of the change
#      (major, minor or patch)
#   c. Spit metadata in file(s) (version, tag, timestamp, module-name, etc.)
#   d. Write a correctly versioned pom.xml
#   e. Tag the repo with the correct version. The git tag can be signed with GPG
#      or not, default behavior is to sign the tag.
#   f. Push the tag
#

cd "$(dirname "${BASH_SOURCE[0]}")/.." || exit 1

RELEASE_LEVEL=$1
MODULE_NAME="${MODULE_NAME:-{{name}}}"
BUILD_DIR="${BUILD_DIR:-target}"
META_OUTPUT_DIR="$BUILD_DIR"

if [ "$RELEASE_LEVEL" = "major" ] || \
   [ "$RELEASE_LEVEL" = "minor" ] || \
   [ "$RELEASE_LEVEL" = "patch" ]
then
    echo "Release \"$MODULE_NAME\" with level '$RELEASE_LEVEL'" >&2
else
  echo "RELEASE_LEVEL '$RELEASE_LEVEL' must be one of [major|minor|patch]" >&2
    exit 1
fi

tag="$(clj -A:metav -m metav.release "$RELEASE_LEVEL" \
  --config-file .metav.edn \
  --module-name-override "$MODULE_NAME" \
  --spit \
  --formats json \
  --output-dir "$META_OUTPUT_DIR" \
  --pom)"
if [ $? -eq 0 ]; then
    echo "Successfully released \"$MODULE_NAME\" to $tag" >&2
else
    echo "Failed to release \"$MODULE_NAME\"!" >&2
    exit 1
fi
