#!/usr/bin/env bash

set -o errexit

new_version="${1}"
if [[ -z ${new_version} ]]; then
    exit 1
fi

pushd $( git rev-parse --show-toplevel ) &>/dev/null

current_version="$( cat .version )"
echo "${current_version} -> ${new_version}"

changelog_file=$( mktemp )
echo "# Write the changelog below; comments will be ignored" >> ${changelog_file}
$EDITOR ${changelog_file}

changelog="$( cat ${changelog_file} | grep -v '^#' | sed 's/^*/  */' )"

sed -i "s,version = \"${current_version}\",version = \"${new_version}\"," node-daemon/pvcnoded/Daemon.py
sed -i "s,version = \"${current_version}\",version = \"${new_version}\"," health-daemon/pvchealthd/Daemon.py
sed -i "s,version = \"${current_version}\",version = \"${new_version}\"," worker-daemon/pvcworkerd/Daemon.py
sed -i "s,version = \"${current_version}\",version = \"${new_version}\"," api-daemon/pvcapid/Daemon.py
sed -i "s,version=\"${current_version}\",version=\"${new_version}\"," client-cli/setup.py
echo ${new_version} > .version

changelog_tmpdir=$( mktemp -d )
cp CHANGELOG.md ${changelog_tmpdir}/
pushd ${changelog_tmpdir} &>/dev/null

echo -e "\n###### [v${new_version}](https://github.com/parallelvirtualcluster/pvc/releases/tag/v${new_version})\n\n${changelog}" >> middle

csplit CHANGELOG.md "/## PVC Changelog/1" &>/dev/null
cat xx00 middle xx01 > CHANGELOG.md
rm xx00 xx01

popd &>/dev/null
mv ${changelog_tmpdir}/CHANGELOG.md CHANGELOG.md
rm -r ${changelog_tmpdir}

deb_changelog_orig="$( cat debian/changelog )"
deb_changelog_new="pvc (${new_version}-0) unstable; urgency=high\n\n${changelog}\n\n -- $( git config --get user.name ) <$( git config --get user.email )>  $( date --rfc-email )\n"

deb_changelog_file=$( mktemp )
echo -e "${deb_changelog_new}" >> ${deb_changelog_file}
echo -e "${deb_changelog_orig}" >> ${deb_changelog_file}
mv ${deb_changelog_file} debian/changelog

git add node-daemon/pvcnoded/Daemon.py health-daemon/pvchealthd/Daemon.py worker-daemon/pvcworkerd/Daemon.py api-daemon/pvcapid/Daemon.py client-cli/setup.py debian/changelog CHANGELOG.md .version
git commit -v

popd &>/dev/null

rm ${changelog_file}

echo
echo "Release message:"
echo
echo "# Parallel Virtual Cluster version ${new_version}"
echo
echo -e "${changelog}" | sed 's/^  \*/*/'
echo
