#!/bin/bash

# ⚠️ This script expects that prepare-next-release has run.

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

CURRENT_VERSION=$(poetry version --no-interaction --short)

GIT_BRANCH=$(git branch --show-current)
if [ "${GIT_BRANCH}" == "main" ]; then
    NEW_VERSION=$(poetry version --no-interaction --short minor)
elif [[ "${GIT_BRANCH}" =~ ^release/[0-9]+\.[0-9]+\.x ]]; then
    NEW_VERSION=${CURRENT_VERSION}
else
    echo "Git branch should be main or a release branch"
    exit 1
fi

APPDATA_RELEASE="<releases>\n"
APPDATA_RELEASE+="    <release version=\"${NEW_VERSION}\" date=\"$(date +"%Y-%m-%d")\">\n"
APPDATA_RELEASE+="      <description>\n"
APPDATA_RELEASE+="        <p>\n"
APPDATA_RELEASE+="          WIP\n"
APPDATA_RELEASE+="        <\/p>\n"
APPDATA_RELEASE+="      <\/description>\n"
APPDATA_RELEASE+="    <\/release>"

update_news_file() {
    local file_path="NEWS.rst"
    local formatted_date
    formatted_date=$(date +"%Y-%m-%d")
    local title="[${NEW_VERSION}] - ${formatted_date}"
    local markup
    markup=$(printf '%*c' ${#title} = | sed 's/ /=/g')

    echo "Updating ${file_path}..."
    sed -i "11 c $title" ${file_path}
    sed -i "12 c $markup" ${file_path}
}

update_readme_file() {
    local file_path="README.rst"

    echo "Updating ${file_path}..."
    sed -i "s/VERSION=.*/VERSION=${NEW_VERSION}/" ${file_path}
}

update_appdata_file() {
    local file_path="data/io.github.orontee.Argos.appdata.xml.in"

    echo "Updating ${file_path}..."
    sed -i "s/<releases>/${APPDATA_RELEASE}/" ${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}
}

update_readme_file
update_meson_conf
update_news_file
update_appdata_file

echo
echo "⚠️ $(tput bold)Remaining tasks:$(tput sgr0)"
echo "- Carefully review the generated code!"
echo "- Complete the file data/io.github.orontee.Argos.appdata.xml.in"
echo "- Update screenshots if needed"
echo "- Update translations if needed"
echo
echo "Then commit, tag, push and call:"
echo
echo "    meson setup builddir"
echo "    meson compile -C builddir create-github-pre-release"
echo
