#!/usr/bin/env bash

set -ex

cd ..

echo "TargetedBranch: ${TARGET_BRANCH}"

echo "Remove all unused containers, networks, images (both dangling and unreferenced) and volumes"
if [ $(docker ps -aq | wc -l) != 0 ]; then
	docker rm -f $(docker ps -aq)
fi
if [ $(docker volume ls -q | wc -l) != 0 ]; then
	docker volume rm -f $(docker volume ls -q)
fi
docker rmi $(docker images | grep cloudera/cloudbreak | tr -s ' ' | cut -d ' ' -f 3) || true

docker network rm cbreak_default || true
docker network prune -f || true

get_latest_version() {
    GIT_ACTIVE_BRANCH=$TARGET_BRANCH
    if [[ $GIT_ACTIVE_BRANCH = master* ]]
    then
        LATEST_VERSION=$(curl "http://release.eng.cloudera.com/hwre-api/getreleaseversion?stack=CB&releaseline=master" | jq -r '.version')
        LATEST_TAG=$(curl "http://release.eng.cloudera.com/hwre-api/listbuilds?stack=CB&release=${LATEST_VERSION}&type=dev" | jq -r '.pass_list_versions[0]')
    elif [[ $GIT_ACTIVE_BRANCH = rc-* ]]
    then
        CUT_VERSION=$(echo $GIT_ACTIVE_BRANCH | cut -f 2 -d '-')
        LATEST_TAG=$(curl "http://release.eng.cloudera.com/hwre-api/listbuilds?stack=CB&release=${CUT_VERSION}.0&type=rc" | jq -r '.pass_list_versions[0]')
    else
        CUT_VERSION=$(echo $GIT_ACTIVE_BRANCH | cut -f 2 -d '-')
        LATEST_TAG=$(curl "http://release.eng.cloudera.com/hwre-api/listbuilds?stack=CB&release=${CUT_VERSION}" | jq -r '.pass_list_versions[0]')
    fi
    echo $LATEST_TAG
}

./gradlew -Penv=jenkins -b build.gradle build -x test -x checkstyleMain -x checkstyleTest -x spotbugsMain -x spotbugsTest --no-daemon -PintegrationTest

if [[ `git status --porcelain` ]]; then
  echo "There are local changes in git, which means some autogenerated classes haven't generated correctly in the PR."
  exit 1
fi

rm -rf integration-test/integcb/.deps
rm -rf integration-test/integcb/.schema
cd integration-test

export PRIMARYKEY_CHECK=true
VERSION=$(get_latest_version) TARGET_BRANCH=$TARGET_BRANCH make runtest-with-code-coverage
RESULT=$?
if [[ $(sudo find integration-test/dumps -name "*.hprof" | tail -1) ]]; then
    sudo cp -v $(sudo find integration-test/dumps -name "*.hprof" | tail -1) .
    sudo chown -R $(whoami) integration-test/dumps/*.hprof
fi
if [[ $RESULT -eq 0 ]]; then
    make revert-db
    make stop-containers
else
    exit $RESULT
fi