# Javascript Node CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-javascript/ for more details
#
version: 2

defaults: &defaults
  working_directory: ~/repo
  docker:
    - image: circleci/node:8.11.3

jobs:
  test:
    <<: *defaults  
    steps:

      - run:
          # By default node is installed as root and we are running as circleci
          # Using sudo causes wierd issues so we just switch to installing globals in our home dir
          name: Setup NPM to make global installs to home directory
          command: | 
            echo "export PATH=$HOME/bin:$PATH" >> $BASH_ENV
            npm set prefix=$HOME

      - checkout

      - restore_cache:
          keys: 
            # when lock file changes, use increasingly general patterns to restore cache
            - "node-v1-{{ .Branch }}-{{ checksum \"package-lock.json\" }}"
            - "node-v1-{{ .Branch }}-"
            - "node-v1-"

      - run:
          name: Install Greenkeeper-Lockfile
          command: npm install -g greenkeeper-lockfile

      - run:
          name: Update Lockfile (Greenkeeper)
          command: greenkeeper-lockfile-update
          
      - run:
          name: Install
          command: npm install

      - run:
          name: Test
          command: npm test

#      - run:
#          name: Integration Test
#          command: if git log -1 --pretty=%B | grep -qF "[skip tests]"; then true; else npm run integration; fi
     
      - run:
          name: Upload Lockfile (Greenkeeper)
          command: greenkeeper-lockfile-upload

      - save_cache:
          paths:
            - node_modules
          key: node-v1-{{ .Branch }}-{{ checksum "package-lock.json" }}

      - persist_to_workspace:
          root: ~/repo
          paths: .
  deploy:
    <<: *defaults
    steps:
      - attach_workspace:
          at: ~/repo
      - run:
          name: Authenticate with registry
          command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/repo/.npmrc
      - run:
          name: Publish package
          command: npm publish
            
workflows:
  version: 2
  test-deploy:
    jobs:
      - test:
          filters:
            tags:
              only: /^v.*/
      - deploy:
          requires:
            - test
          filters:
            tags:
              only: /^v.*/
            branches:
              ignore: /.*/
