#!/bin/sh

set -eu

export SQUAD_CLIENT_RELEASE=1
EDITOR=${EDITOR-editor}

v=$(python3 -c 'from squad_client.version import __version__ as v; print(v)')
if git rev-parse --verify --quiet "v${v}" >/dev/null; then
    echo "Version ${v} has already been released. Let's prepare a new one"
    $EDITOR squad_client/version.py
fi

v=$(python3 -c 'from squad_client.version import __version__ as v; print(v)')
if git rev-parse --verify --quiet "v${v}" >/dev/null; then
    echo "Version ${v} has already been released. Aborting"
    exit 1
fi

if ! grep -q "^# $v" CHANGELOG.md; then
    echo "Let's now document the changes in CHANGELOG.md"
    $EDITOR CHANGELOG.md
fi

if ! grep -q "^# $v" CHANGELOG.md; then
    echo "E: Version $v is not documented in CHANGELOG.md. Please do that before releasing"
    exit 1
fi

changed=$(git diff-index --name-only HEAD -- | (grep -v 'CHANGELOG.md\|squad_client/version.py' || true))
if [ -n "$changed" ]; then
    echo "E: uncommited changes found; cannot release like this"
    echo "I: changed files:"
    echo "$changed"
    echo "I: CHANGELOG.md and squad_client/version.py are excused, they would be committed automatically"
    exit 1
fi

if [ "${TEST:-yes}" != "no" ]; then
    ./manage.py test
fi

# Build squad-client pip package and docker container
./scripts/build "v$v"
rm -rf build/ dist/ *.egg-info/

# Commit changes and push the new tag
git commit --message "New release: ${v}" CHANGELOG.md squad_client/version.py || true
git tag -s -m "SQUAD Client release $v" "v$v"
git push
git push --tags
