# Copyright 2019 PrivateStorage.io, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

version: 2

aliases:
  - &PREPARE_VIRTUALENV
    run:
      name: "Prepare virtualenv"
      command: |
        virtualenv venv
        . venv/bin/activate
        pip install --upgrade certifi pip
        pip install ${PIP_REQUIREMENTS}

jobs:
  documentation:
    docker:
      - image: "circleci/python:3.7"

    environment:
      PIP_REQUIREMENTS: "-r docs/requirements.txt"

    steps:
      - "checkout"

      - <<: *PREPARE_VIRTUALENV

      - run:
          name: "Sphinx Documentation Build"
          command: |
            . venv/bin/activate
            sphinx-build docs/source docs/build

      - store_artifacts:
          path: "docs/build"
          destination: "docs"

  tests:
    docker:
      # Run in a highly Nix-capable environment.
      - image: "nixorg/nix:circleci"

    environment:
      CODECOV_TOKEN: "cc6e4697-4337-4506-88af-92b8f8ca6b22"
      # Specify a revision of NixOS/nixpkgs to run against.  This essentially
      # pins the majority of the software involved in the build.  This
      # revision is selected arbitrarily.  It's somewhat current as of the
      # time of this comment.  We can bump it to a newer version when that
      # makes sense.  Meanwhile, the platform won't shift around beneath us
      # unexpectedly.
      NIXPKGS_REV: "5d5cd70516001e79516d2ade8bcf31df208a4ef3"

    steps:
      - run:
          # Get NIX_PATH set for the rest of the job so that the revision of
          # nixpkgs we selected will be used everywhere Nix pulls in software.
          # There is no way to set an environment variable containing the
          # value of another environment variable on CircleCI except to use
          # the `BASE_ENV` feature as we do here.
          name: "Setup NIX_PATH Environment Variable"
          command: |
            echo "export NIX_PATH=nixpkgs=https://github.com/NixOS/nixpkgs-channels/archive/$NIXPKGS_REV.tar.gz" >> $BASH_ENV

      - "checkout"

      - run:
          name: "Run Test Suite"
          command: |
            nix-build --argstr hypothesisProfile ci --arg collectCoverage true --attr doc

      - run:
          name: "Report Coverage"
          command: |
            nix-shell -p 'python.withPackages (ps: [ ps.codecov ])' --keep CODECOV_TOKEN --run \
              codecov ./result-doc/share/doc/*/.coverage

workflows:
  version: 2
  everything:
    jobs:
      - "documentation"
      - "tests"
