#!/usr/bin/env bash

set -e

if ! command -v hatch > /dev/null 2>&1; then
    echo "Hatch is not installed. Make sure it is available: 'pip install hatch'. Aborting..."
    exit 1
fi

if ! command -v jq > /dev/null 2>&1; then
    echo "jq is not installed. Make sure it is available. Aborting..."
    exit 1
fi

echo "Cleaning previously built artifacts..." && hatch clean

CURRENT_VERSION=$(hatch version)

if [[ $CURRENT_VERSION =~ \.dev ]]; then
    RELEASE_VERSION="${CURRENT_VERSION%%.dev*}"
else
    echo "Current version is not properly setup as dev version. Aborting..."
    exit 1
fi

echo "Releasing version $RELEASE_VERSION..." && hatch version "${RELEASE_VERSION}"

jq --arg release_version "${RELEASE_VERSION}" '.version = $release_version' < package.json > package.json.tmp && mv package.json.tmp package.json

git add src/openllm/__about__.py package.json && git commit -sm "infra: prepare for release ${RELEASE_VERSION} [generated]"
git push origin main

echo "Building artifacts for releasing..." && hatch build

echo "Releasing version ${RELEASE_VERSION}" && hatch publish

echo "Finish releasing version ${RELEASE_VERSION}"

echo "Releasing tag ${RELEASE_VERSION}..." && git tag -a "v${RELEASE_VERSION}" -sm "Release ${RELEASE_VERSION} [generated by tools/release]"
git push origin "v${RELEASE_VERSION}"

echo "Bumping version to dev..." && hatch version patch && hatch version dev

jq --arg release_version "$(hatch version)" '.version = $release_version' < package.json > package.json.tmp && mv package.json.tmp package.json

git add src/openllm/__about__.py package.json && git commit -sm "infra: bump to dev version of $(hatch version) [generated]"
git push origin main
