# Java Maven CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-java/ for more details
#
version: 2
jobs:
  build:
    docker:
      # specify the version you desire here
      - image: circleci/openjdk:8-jdk
      
      # Specify service dependencies here if necessary
      # CircleCI maintains a library of pre-built images
      # documented at https://circleci.com/docs/2.0/circleci-images/
      # - image: circleci/postgres:9.4

    working_directory: ~/repo

    environment:
      # Customize the JVM maximum heap limit
      MAVEN_OPTS: -Xmx3200m
      DOCKER_VERSION: 17.04.0-ce
    
    steps:
      - checkout

      - setup_remote_docker:
          docker_layer_caching: true 

      - run:
          name: Install Docker client
          command: |
            if [ ! -x /usr/bin/docker ]; then
              curl -fsSL https://get.docker.com/builds/Linux/x86_64/docker-${DOCKER_VERSION}.tgz | tar xz -C /usr/bin --strip-components 1
            fi

      # Download and cache dependencies
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "pom.xml" }}
          # fallback to using the latest cache if no exact match is found
          - v1-dependencies-

      - run: mvn dependency:go-offline -P image

      - save_cache:
          paths:
            - ~/.m2
          key: v1-dependencies-{{ checksum "pom.xml" }}
        
      # build and run tests
      - run: sudo apt-get install -y rsync
      - run: mvn clean package --batch-mode  -P image -Dfabric8.mode=kubernetes

push_images:
  deploy:
    command: |
      if [ "${CIRCLE_PROJECT_USERNAME}" != "Apicurio" ]; then
        exit 0
      fi
      if [ ! -x /usr/bin/docker ]; then
        curl -fsSL https://get.docker.com/builds/Linux/x86_64/docker-${DOCKER_VERSION}.tgz | tar xz -C /usr/bin --strip-components 1
      fi

      # Building the master branch
      if [ "${CIRCLE_BRANCH}" == "master" ]; then
        docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
        docker push apicurio/apicurito-ui:latest | cat -
      fi

      # Building a tag
      if [[ "${CIRCLE_TAG}" =~ ^[0-9]+(\.[0-9]+){2} ]]; then
        docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
        for image in ${IMAGES} ; do
          docker push apicurio/apicurito-ui:${CIRCLE_TAG} | cat -
          docker tag apicurio/apicurito-ui:${CIRCLE_TAG} apicurio/apicurito-ui:$(echo ${CIRCLE_TAG} | sed -e 's/\.[0-9][0-9]*$//')
          docker push apicurio/apicurito-ui:$(echo ${CIRCLE_TAG} | sed -e 's/\.[0-9][0-9]*$//')
        done
      fi
