---
version: 2

buildSteps: &buildSteps
  - checkout
  - run:
      name: install-npm
      command: npm install
  - run:
      name: test
      command: npm test
  - persist_to_workspace:
      # Persist all job output, so we can (potentially) use it for deploys
      root: ../
      paths:
        - ./node-*

jobs:
  "node-6":
    docker:
      - image: circleci/node:6
    working_directory: ~/node-6
    steps: *buildSteps

  "node-8":
    docker:
      - image: circleci/node:8
    working_directory: ~/node-8
    steps: *buildSteps

  "node-10":
    docker:
      - image: circleci/node:10
    working_directory: ~/node-10
    steps: *buildSteps

  deploy:
    # For this to work NPM_TOKEN must be set for the account used for publishing
    docker:
      - image: circleci/node:8
    steps:
      - attach_workspace:
          at: .
      - run:
          name: install-npm-4
          command: sudo npm install -g npm@4
      - run:
          name: Login to npm
          command: |
            echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
            npm whoami
      - deploy:
          name: Deploy to npm
          # Output used for publish is from node 8 build
          command: cd node-8 && npm publish

workflows:
  version: 2
  build:
    jobs:
      - "node-6":
          # Run for all tags (required to allow the deploy to trigger on version tags)
          filters:
            tags:
              only: /.*/
      - "node-8":
          # Run for all tags (required to allow the deploy to trigger on version tags)
          filters:
            tags:
              only: /.*/
      - "node-10":
          # Run for all tags (required to allow the deploy to trigger on version tags)
          filters:
            tags:
              only: /.*/
      - deploy:
          # Deploy passing builds if they're tagged with a version
          requires:
            - "node-6"
            - "node-8"
            - "node-10"
          filters:
            tags:
              only: /^v\d+\.\d+\.\d+$/
            branches:
              ignore: /.*/
