# 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.1

jobs:
  test:
    docker:
      - image: "nixos/nix:2.2.1"

    environment:
      NIXPKGS_REV: "3c83ad6ac13b67101cc3e2e07781963a010c1624"

    steps:
      - run:
          name: "Setup NIX_PATH Environment Variable"
          command: |
            echo "export NIX_PATH=nixpkgs=https://github.com/NixOS/nixpkgs/archive/$NIXPKGS_REV.tar.gz >> $BASH_ENV"

      - run:
          name: "Install CA Certificates"
          command: |
            # Required for cache and artifact interactions.  Though we use a
            # nix image, it's actually an alpine base...  The CircleCI cache
            # management and artifact uploader don't know how to use the nix
            # ca bundle we could install.
            apk update
            apk add ca-certificates

      - restore_cache:
          name: "Restore Nix Store Paths"
          keys:
            - paymentserver-nix-store-v1-{{ .Environment.NIXPKGS_REV }}
            - paymentserver-nix-store-v1-

      - run:
          name: "Install Git"
          command: |
            # Required for the checkout step.
            nix-env -i git openssh

      - "checkout"

      - restore_cache:
          # Read about caching dependencies: https://circleci.com/docs/2.0/caching/
          name: "Restore Cached Dependencies"
          keys:
            - paymentserver-v1-{{ checksum "stack.yaml" }}-{{ checksum "PaymentServer.cabal" }}
            - paymentserver-v1-{{ checksum "stack.yaml" }}

      - run:
          name: "Run Tests"
          command: |
            nix-shell shell.nix --run "stack test --no-terminal --coverage"

      - save_cache:
          name: "Cache Dependencies"
          key: paymentserver-v1-{{ checksum "stack.yaml" }}-{{ checksum "PaymentServer.cabal" }}
          paths:
            - "/root/.stack"
            - ".stack-work"

      - save_cache:
          name: "Cache Nix Store Paths"
          key: paymentserver-nix-store-v1-{{ .Environment.NIXPKGS_REV }}

workflows:
  version: 2
  everything:
    jobs:
      - "test"
