#!/bin/bash -eu

VERSION=$(grep "^__version__" dials_data/__init__.py | cut -d'"' -f 2)
BASETAG=v${VERSION}
git tag --list | grep "^${BASETAG}$" || {
  echo Searching for tag on remote
  if git fetch origin tag ${BASETAG}; then
    echo Tag found on remote. Deepening checkout...
    git fetch --shallow-exclude ${BASETAG}
    git fetch --deepen 1
  else
    echo "Tag not found on remote. Let's make a new one!"
    git tag ${BASETAG}
    echo "##[warning]Tag ${BASETAG} is missing on your repository. Packages generated during the build will not have reliable version numbers"
  fi
}

DEPTH=$(git rev-list ${BASETAG}..HEAD --count --first-parent)
REAL_VERSION=${VERSION%.0}.${DEPTH}
echo Setting package version from ${VERSION} to ${REAL_VERSION}
sed -i "s/^__version__ =.*/__version__ = \"${REAL_VERSION}\"/" dials_data/__init__.py
sed -i "s/^version = .*$/version = ${REAL_VERSION}/" setup.cfg

COMMIT=$(git rev-parse --verify HEAD)
echo Setting package commit to ${COMMIT}
sed -i "s/^__commit__ =.*/__commit__ = \"${COMMIT}\"/" dials_data/__init__.py
