version: 2
jobs:
  build:
    working_directory: ~/rookeries_ci
    docker:
      - image: dorianpula/circleci-test:1.0.0

    steps:
      - checkout
      - setup_docker_engine

      # Enable caching: https://circleci.com/blog/how-to-build-a-docker-image-on-circleci-2-0/
      - restore_cache:
          keys:
            - v1-{{ arch }}-{{ .Branch }}
          paths:
            - /caches/rookeries-app.tar

      - run:
          name: Load Docker image layer cache
          command: |
            set +o pipefail
            docker load --input /caches/rookeries-app.tar | true

      - run:
          name: Build Rookeries Docker image
          command: |
            docker build --cache-from=dorianpula/rookeries:latest --tag dorianpula/rookeries:latest .

      - run:
          name: Save Docker image layer cache
          command: |
            mkdir -p /caches
            docker save --output /caches/rookeries-app.tar dorianpula/rookeries:latest

      - save_cache:
          key: v1-{{ arch }}-{{ .Branch }}-{{ epoch }}
          paths:
            - /caches/rookeries-app.tar

      # Run tests
      - run:
          name: Test Style
          command: make test-style

      - run:
          name: Test API
          command: make test-api

      - run:
          name: Test UI
          command: make test-ui

      - deploy:
          name: Upload Latest to Docker Hub
          command: |
            if [ "${CIRCLE_BRANCH}" == "master" ]; then
              docker login -u $DOCKER_USER -p $DOCKER_PASS
              docker push dorianpula/rookeries:latest
            fi

      - deploy:
          name: Upload Tagged Release to Docker Hub
          command: |
            if [ -n "${CIRCLE_TAG}" ]; then
              docker login -u $DOCKER_USER -p $DOCKER_PASS
              docker tag dorianpula/rookeries:latest dorianpula/rookeries:${CIRCLE_TAG}
              docker push dorianpula/rookeries:${CIRCLE_TAG}
            fi
