version: 2
jobs:
  build:
    docker:
      - image: circleci/node:6


    working_directory: ~/kes
    steps:
      - checkout

      # restore cache
      - restore_cache:
          keys:
            - deploy-{{ .Branch }}-{{ checksum "package.json" }}

      - run:
          name: Install
          command: npm install
      
      - run:
          name: Lint
          command: |
            ./node_modules/.bin/eslint src --ext .js
            ./node_modules/.bin/eslint bin --ext .js

      # save cahce
      - save_cache:
          key: deploy-{{ .Branch }}-{{ checksum "package.json" }}
          paths:
            - ~/kes/node_modules

      - run:
          name: Test Examples
          command: |
            mkdir ~/example1
            cp -r examples/lambdas ~/example1/.kes
            cd ~/example1/
            ~/kes/bin/cli.js cf compile
            ~/kes/bin/cli.js cf validate

            cd ~/kes
            ./bin/cli.js cf compile --kes-folder examples/full
            ./bin/cli.js cf validate --kes-folder examples/full
            ./bin/cli.js cf validate --kes-folder examples/nested

            npm run test

      - run:
          name: Integration Tests
          command: npm run integration-test

      - add_ssh_keys:
          fingerprints:
             - "8f:58:d1:7d:1f:b0:ed:cc:fd:c9:46:cb:ee:6b:40:86"
      - run:
          name: docs
          command: |
            if [ "${CIRCLE_BRANCH}" == "master" ]; then
              cd ~/kes
              npm run html-docs
              cd _docs
              git init
              git config user.name "Devseed-CI"
              git config user.email "dev@developmentseed.org"
              git add .
              git commit -m "CI deploy [skip ci]"
              git remote add origin git@github.com:developmentseed/kes.git
              git push origin master:gh-pages --force
            fi

      - run:
          name: Deploy
          command: |
            if [ "${CIRCLE_BRANCH}" == "master" ]; then
              cd ~/kes
              echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc
              npm publish || echo 'npm publishing failed'
            fi

      
