version: 2

jobs:
  build:
    docker:
      - image: circleci/node:stretch-browsers
      - image: couchdb
        environment:
        - COUCHDB_USER: admin
        - COUCHDB_PASSWORD: admin
    steps:
      - checkout
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "package.json" }}
          - v1-dependencies-
      - run: npm install
      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "package.json" }}

      - setup_remote_docker

      # Install CouchDB 2
      # Wait for DB to be ready
      - run: ./node_modules/wait-on/bin/wait-on tcp:5984
      # Create system DBs
      - run: curl -X PUT http://admin:admin@localhost:5984/_users
      - run: curl -X PUT http://admin:admin@localhost:5984/_replicator
      - run: curl -X PUT http://admin:admin@localhost:5984/_global_changes

      # Enable CORS
      - run: sudo npm install -g add-cors-to-couchdb
      - run: add-cors-to-couchdb http://localhost:5984 -u admin -p admin

      # Change the host as we want a standard host that will work even from within the Docker
      # container
      - run: HOST_IP=`/sbin/ip route | awk '/eth0 proto/ { print $9 }'` && sed -i "s/127.0.0.1/$HOST_IP/g" test/config.json

      - run: npm run assert-beautified
      - run: npm run jshint
      - run: npm run node-full-test
      - run: npm run browser-test
      - run: npm run browser-coverage-full-test
