#!/bin/sh

set -eu

v=$(python3 -c 'from squad.version import __version__ as v; print(v)')
if git rev-parse --verify --quiet "${v}^{tag}" >/dev/null; then
    echo "It seems version ${v} has already been released. Aborting"
    exit 1
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

./manage.py test

# TODO: require all changes committed to git
if ! git diff-index --quiet --exit-code HEAD --; then
    echo "E: uncommited changes found; cannot release like this"
    exit 1
fi

if ! ./scripts/check-ci; then
    printf "Are you sure you want to continue? [y/N]"
    read -r confirm
    if [ "$confirm" != 'y' ] && [ "$confirm" != 'Y' ]; then
        exit 1
    fi
fi

# build
rm -rf dist/ *.egg-info/
python3 setup.py sdist bdist_wheel

# test
tar=$(mktemp tar.XXXXXXXXX)
git=$(mktemp git.XXXXXXXXX)
trap cleanup INT TERM EXIT
cleanup() {
    rm -rf "$tar" "$git"
}
git ls-tree -r --name-only HEAD | grep -v '^\.' | sort > "$git"
tar taf dist/squad-${v}.tar.gz | cut -d / -f 2- | grep -v '\(/$\|^$\|PKG-INFO\|egg-info\|static\/\(angularjs\|font-awesome\|bootstrap\|lodash\)\)' | sort > "$tar"
diff -u "$tar" "$git"

# sign & upload
for f in dist/*; do
    gpg --detach-sign --armor "$f"
done
twine upload dist/*

git tag -s -m "SQUAD release $v" "$v"
git push
git push --tags

rm -rf build/
rm -rf dist/
