#! /usr/bin/env bash

TOML=$1

if [ ! -f $TOML ]; then
    echo "No toml passed in. Assuming pyproject.toml"
    TOML=pyproject.toml
    if [ ! -f $TOML ]; then
        echo "No pyproject.toml!"
        exit 1
    fi
fi

DESC=$(git describe --tags)
# DESC either contains A.B-C-g<sha> more generally, or just A.B if we're on the tagged commit where
# the tag is "A.B" from the git repo. C is the count away from the tag and <sha> is the short
# commit sha

if [[ -z $DESC ]]; then
    # If it isn't set up, start at 0
    echo "No git tags set up. Start at 0.0.0"
    DESC="0.0.0"
fi
DESC=$(echo $DESC | sed "s/-g.*//" | sed "s/-/./g")

echo "Setting version as $DESC"
sed -i "s/version = .*/version = \"$DESC\"/" $TOML

grep -q "$DESC" $TOML
if [[ $? != "0" ]]; then
    echo "Did not find new version in $TOML. Exiting"
    exit 1
fi
