#!/bin/bash

cd "`dirname \"$0\"`"
cd ..

set -e

COMMIT=`git log --pretty="%H" -1`
# find out branch
# * master
BRANCH=`git branch --no-color | grep '\*' | grep -oE '[^ ]+$'`
# detect detached head state
# * (detached from 05e4d35)
if echo "$BRANCH" | grep -q ')'; then
    BRANCH="$COMMIT"
    echo "Working with commit $COMMIT in detached head state."
else
    echo "Working with commit $COMMIT on branch $BRANCH."
fi
git fetch origin google-play || true
git checkout google-play
git checkout "$COMMIT"

echo "Retrieve the changes for google play."
if ! ( git pull --ff-only origin google-play || git merge google-play -m "Merge google-play branch." ) ; then
    echo "ERROR: Merge failed. Please update the google-play branch."
    exit 1
fi

success=true

if [ -n "$keystore_password" ]; then
    echo "Create release files."
    if ! ( gradle assembleRelease && gradle bundleRelease ); then
        success=false
    fi
else
    echo "Can not sign the release, so checking the build."
    if ! gradle build check; then
        success=false
    fi
fi

echo "Collect APK files"
.travis/collect-apks "-google-play"

echo "Revert changes if there are any."
git stash || true
git checkout "$BRANCH"

echo "Build did `[ "$success" == "false" ] && echo -n 'not '`succeed."
[ "$success" == "true" ]
