#!/bin/bash -ex

main() {
  set -ex -o pipefail

  export INTEGRATIONTEST_SUITE_FILES=file:/it/src/main/resources/testsuites/v4/mock/config-change-migration-tests.yaml
  export AWS=false
  export INTEGRATIONTEST_UMS_HOST=thunderhead-mock
  export INTEGRATIONTEST_UMS_PORT=8982
  export INTEGRATIONTEST_CDL_HOST=thunderhead-mock
  export INTEGRATIONTEST_CDL_PORT=8982
  export INTEGRATIONTEST_AUTHDISTRIBUTOR_HOST=thunderhead-mock
  export INTEGRATIONTEST_THREADCOUNT=4
  export RESTARTABLE_SERVICES="cloudbreak"
  export INTEGRATIONTEST_TESTSUITE_CLEANUP=false
  export INTEGRATIONTEST_TESTSUITE_CLEANUPONFAILURE=false

  gh_label=$(curl -H "Accept: application/json" https://github.infra.cloudera.com/api/v3/repos/cloudbreak/cloudbreak/pulls/$PULL_REQUEST_NUMBER |jq '.labels[]?|select(.name=="config_change_int_test")|.name')
  if [[ -z "$gh_label" ]]
  then
    echo "no need for build"
  else
    $(pwd)/gradlew -Penv=jenkins -b build.gradle build --quiet --warning-mode none \
        -x test \
        -x checkstyleMain \
        -x checkstyleTest \
        -x spotbugsMain \
        -x spotbugsTest \
        --no-daemon --quiet --parallel -PintegrationTest >> build.log

    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
    export VERSION=$(get_latest_version)
    export TARGET_BRANCH=$BRANCH
    make without-build
    sed -i '/^export CB_JAVA_OPTS/ s/.$/ -Dcb.platform.default.rootVolumeSize.MOCK=300" /' integcb/Profile
    ls -la
    ls -la integcb/
    ls -la testuser_home/
    make docker-compose-after-config-change stop-containers check-results
    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
  fi
}

source $(pwd)/.github/workflows/pull-request/steps/prerequisites.sh
main "$@"