#!/bin/bash

cd "${MESON_SOURCE_ROOT}" || {
    eho "Failed to switch to source root"
    exit 1
}

if [[ -n "$(git status --porcelain)" ]]; then
    echo "Unclean repository!"
    exit 1
fi

GIT_BRANCH=$(git branch --show-current)
if [ "${GIT_BRANCH}" == "main" ]; then
    SCOPE="preminor"
elif [[ "${GIT_BRANCH}" =~ ^release/[0-9]+\.[0-9]+\.x ]]; then
    SCOPE="patch"
else
    echo "Git branch should be main or a release branch"
    exit 1
fi

CURRENT_VERSION=$(poetry version --short)
NEW_VERSION=$(poetry version --short "${SCOPE}")

git add pyproject.toml
echo "Version set to ${NEW_VERSION}"

NEWS_HEADER="[Unreleased]\n============\n\nAdded\n-----\n\nChanged\n-------\n\nRemoved\n-------\n"

CHANGELOG_DATE=$(LANG=C date +"%a, %d %b %Y %H:%M:%S %z")
CHANGELOG_AUTHOR="$(git config user.name) <$(git config user.email)>"
CHANGELOG="argos (${NEW_VERSION}-1) UNRELEASED; urgency=medium

  * ${NEW_VERSION} release.

 -- ${CHANGELOG_AUTHOR}  ${CHANGELOG_DATE}
"

update_news_file() {
    local file_path="NEWS.rst"

    echo "Updating ${file_path}..."
    sed -i "11 i ${NEWS_HEADER}" ${file_path}

    git add ${file_path}
}

update_meson_conf() {
    local file_path="meson.build"

    echo "Updating ${file_path}..."
    sed -i "s/version: '${CURRENT_VERSION}'/version: '${NEW_VERSION}'/" ${file_path}

    git add ${file_path}
}

update_news_file
update_meson_conf

git commit -m "Prepare for next release"
