version: 2.1

# reusable 'executor' object for jobs
executors:
  go:
    docker:
      - image: circleci/golang:1.12.8
    environment:
      - TEST_RESULTS: /tmp/test-results # path to where test results are saved

jobs:
  go-fmt-and-vet:
    executor: go
    steps:
      - checkout

      # Restore go module cache if there is one
      - restore_cache:
          keys:
            - serf-modcache-v1-{{ checksum "go.mod" }}

      - run: go mod download

      # Save go module cache if the go.mod file has changed
      - save_cache:
          key: serf-modcache-v1-{{ checksum "go.mod" }}
          paths:
            - "/go/pkg/mod"

      # check go fmt output because it does not report non-zero when there are fmt changes
      - run:
          name: check go fmt
          command: |
            files=$(go fmt ./...)
            if [ -n "$files" ]; then
              echo "The following file(s) do not conform to go fmt:"
              echo "$files"
              exit 1
            fi
      - run: go vet ./...

  go-tests:
    executor: go
    steps:
      - checkout
      - run: mkdir -p $TEST_RESULTS
      - run: make bin

      # Restore go module cache if there is one
      - restore_cache:
          keys:
            - serf-modcache-v1-{{ checksum "go.mod" }}

      # run go tests with gotestsum
      - run: |
          PACKAGE_NAMES=$(go list ./...)
          gotestsum --format=short-verbose --junitfile $TEST_RESULTS/gotestsum-report.xml -- $PACKAGE_NAMES
      - store_test_results:
          path: /tmp/test-results
      - store_artifacts:
          path: /tmp/test-results

  build-website:
    # setting the working_directory along with the checkout path allows us to not have
    # to cd into the website/ directory for commands
    working_directory: ~/project/website
    docker:
      - image: hashicorp/middleman-hashicorp:0.3.35
    steps:
      - checkout:
          path: ~/project

      # restores gem cache
      - restore_cache:
          key: static-site-gems-v1-{{ checksum "Gemfile.lock" }}

      - run:
          name: install gems
          command: bundle check || bundle install --path vendor/bundle --retry=3

      # saves gem cache if we have changed the Gemfile
      - save_cache:
          key: static-site-gems-v1-{{ checksum "Gemfile.lock" }}
          paths:
            - ~/project/website/vendor/bundle

      - run:
          name: middleman build
          command: bundle exec middleman build

      - run:
          name: website deploy
          command: ./scripts/deploy.sh

workflows:
  version: 2
  go-tests:
    jobs:
      - go-fmt-and-vet
      - go-tests:
          requires:
            - go-fmt-and-vet
  website:
    jobs:
      - build-website:
          context: static-sites
          filters:
            branches:
              only: master
