#! /bin/bash
# This should be run from the root of the repository:
#     ci/prep_and_tag_release <tag>
#
# This script will update the README.md links to point to the versioned links,
# commit the change, tag the new commit, and revert the change to keep the repo pointing to master. 
#
# Args:
#     tag: The tag for the release.
#          Tags should follow the version style of previous tags.
#          See documentation for more information on version numbering.

if [ $# -eq 0 ]; then
    echo "Please specify the release tag. E.g: v0.1.0-rc1"
    exit 1
fi

tag=$1

tag_regex="^v[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z]+[0-9]+)*$"
if [[ ! $tag =~ $tag_regex ]]; then
    echo "$tag is not a valid tag. Expected tag matching regex: $tag_regex"
    exit 1
fi

branch=$(git branch --show-current)

branch_regex="^release-[0-9]+\.[0-9]+\.x$"
if [[ ! $branch =~ $branch_regex ]]; then
    echo "Releases should only be made from release branches. You are on: $branch"
    exit 1
fi

cp README.md README.md.bak

sed -i -e "s|\(fitbenchmarking/Build%20and%20Publish\)[^\?]*|\1/${tag}|" \
    -e "s|\(actions/workflows/release.yml\).*)|\1?query=branch%3A${tag})|" \
    -e "s|\(fitbenchmarking/Tests\)[^\?]*|\1/${tag}|" \
    -e "s|\(actions/workflows/main.yml\).*)|\1?query=branch%3A${tag})|" \
    -e "s|\(/readthedocs/fitbenchmarking\)[^\?]*|\1/${tag}|" \
    -e "s|\(readthedocs.io/en\).*)|\1/${tag})|" \
    README.md

git add README.md
git commit -m "Prepare release: ${tag}"
git tag -a "${tag}" -m "Tag generated by prep_and_release.sh"

mv README.md.bak README.md

git add README.md
git commit -m "Reset README.md to follow master"
