#!/bin/sh

set -eu

cd $(readlink -f $(dirname $0)/..)

current_version=$(python3 -c "import tuxmake; print(tuxmake.__version__)")
version=${1:-}
if [ -z "${version}" ]; then
    version=$(echo ${current_version} | awk -F . '{OFS = "." ; $3 = "0"; $2 += 1; print($0)}')
fi
relnotes=.git/relnotes-${version}.txt
git=${git:-git}
flit=${flit:-flit}

if [ -n "$(git tag --list v${version})" ]; then
    echo "Version ${version} already released. Bump the version in tuxmake/__init__.py to make a new release"
    exit 1
fi

if ! git diff-index --exit-code --quiet HEAD; then
    git status
    echo "Commit all changes before releasing"
    exit 1
fi

if [ ! -f ${relnotes} ]; then
    printf "${version} release\n\n" > ${relnotes}
    git log --no-merges --reverse --oneline $(git tag | sort -V | tail -1).. >> ${relnotes}
fi

${EDITOR} ${relnotes}
echo "Release notes: "
sed -e 's/^/| /' ${relnotes}

read -p "Press ENTER to release version ${version} with the release notes above, or ctrl-c to abort" input

# update version number
sed -i -e "s/^__version__.*/__version__ = \"${version}\"/" tuxmake/__init__.py
sed -i -e "s/^Version:.*/Version:   ${version}/" tuxmake.spec
sed -i -e "1 { s/(.*)/(${version}-1)/ }" debian/changelog
$git commit -m "Release ${version}" tuxmake/__init__.py tuxmake.spec debian/changelog

$git push
$git tag --sign --file=${relnotes} v${version}
$flit publish
$git push --tags
rm -f ${relnotes}

./scripts/build-src-pkgs >/dev/null
