#!/usr/bin/env sh
THIS_FILE=$0
TARGET_BRANCH=$1

if [ -z "$TARGET_BRANCH" ]; then
  echo "No target branch provided, not running branch-to-branch migration test."
  echo "Please run this script again as: './scripts/migration-cross-branch-test.sh <BRANCH_NAME>'"
  exit 0
fi

# Stash any current changes to later unstash
CURRENT_STASHES=$(git stash list | wc -l)
git stash
NEW_STASHES=$(git stash list | wc -l)

if [ "$CURRENT_STASHES" != "$NEW_STASHES" ]; then
  echo "Successfully stashed your current changes"
  STASHED="yes"
fi

# Run migration test with DB population on target branch, this should populate the DB and leave it for the next run
git checkout "$TARGET_BRANCH"
git pull

# Stupid self-check to see whether this is not the first time this script is introduced
if [ ! -f "$THIS_FILE" ]; then
  echo "Target branch does not contain script for migrations, assuming this is the first cross-branch run."
  git checkout -

  if [ -n "$STASHED" ]; then
    git stash pop
  fi

  exit 0
fi

./gradlew clean
./gradlew test --tests "*.MigrationApplicationTest" -i -x generateGitProperties
EXIT_CODE=$?

git checkout -
if [ -n "$STASHED" ]; then
  git stash pop
fi

if [ ! $EXIT_CODE -eq 0 ]; then
  echo "Non-zero exit code from migration test, returning"
  exit 1
fi

# Then run the migration test on current branch, but without loading a new database to see if data transfer is okay

./gradlew clean
./gradlew test --tests "*.NoDbMigrationApplicationTest" -i -x generateGitProperties
exit $?

