#!/usr/bin/env bash

# TODO: prepare changelog

set -e

if (( "$#" != 1 ))
then
    echo "Tag has to be provided"
    exit 1
fi

./bin/subtree-split

CURRENT_BRANCH=`git rev-parse --abbrev-ref HEAD`

for REMOTE in origin core paypal-express-checkout paypal-pro-checkout paypal-pro-hosted authorize-net-aim be2bill paypal-masspay \
    paypal-ipn paypal-rest offline payex klarna-checkout klarna-invoice stripe sofort skeleton
do
    echo ""
    echo ""
    echo "Releasing $REMOTE";

	TMP_DIR="/tmp/payum-repo"
    REMOTE_URL=`git remote get-url $REMOTE`

    rm -rf $TMP_DIR;
    mkdir $TMP_DIR;

    (
        cd $TMP_DIR;
        git clone $REMOTE_URL . --depth=200
        git checkout $CURRENT_BRANCH;
        # gsort comes with coreutils packages. brew install coreutils
        LAST_RELEASE=$(git tag -l [0-9].* | gsort -V | tail -n1 )
        if [[ -z "$LAST_RELEASE" ]]; then
            echo "There has not been any releases. Releasing $1";

            git tag $1 -s -m "Release $1"
            git push origin --tags
        else
            echo "Last release $LAST_RELEASE";

            CHANGES_SINCE_LAST_RELEASE=$(git log "$LAST_RELEASE"...master)
            CHANGES_SINCE_LAST_RELEASE="$CHANGES_SINCE_LAST_RELEASE" | xargs echo -n
            if [[ ! -z "$CHANGES_SINCE_LAST_RELEASE" ]]; then
                echo "There are changes since last release. Releasing $1";

                git tag $1 -s -m "Release $1"
                git push origin --tags
            else
                echo "No change since last release.";
            fi
        fi
    )
done
