version: 2

jobs:
  test:
    docker:
      - image: circleci/node:8.9.1
      - image: circleci/mongo:3.6-jessie
    steps:
      - checkout
      - run:
          name: Install
          command: npm install
      - run:
          name: Run tests
          command: npm test

  publish:
    docker:
      - image: circleci/node:8.9.1
    steps:
      - checkout
      - add_ssh_keys
      - run:
          name: Add github to known_hosts
          command: ssh-keyscan github.com >> ~/.ssh/known_hosts
      - attach_workspace:
          at: ~/repo
      - run:
          name: Authenticate with registry
          command: echo "//registry.npmjs.org/:_authToken=$npm_TOKEN" > ~/project/.npmrc
      - run:
          name: Publish package
          command: |
            # tag the master branch and push
            git config --global user.email "circleci@varpass.com"
            git config --global user.name "Circle CI"
            git reset --hard HEAD
            git tag "v`grep '"version"' package.json | egrep -o "[0-9]+.[0-9]+.[0-9]+"`"
            git push --tags
            # checkout development and bump the version
            git checkout -b circle-ci-version-bump origin/development
            git pull
            npm --no-git-tag-version version patch
            git add package.json
            git commit -m "`grep '"version"' package.json | egrep -o "[0-9]+.[0-9]+.[0-9]+"`"
            git push -u origin circle-ci-version-bump:development --follow-tags
            # checkout master again and delete our local branch
            git checkout master
            git branch -D circle-ci-version-bump
            # publish
            npm publish ~/project/
            
workflows:
  version: 2
  test_and_publish:
    jobs:
      - test
      - publish:
          requires:
            - test
          filters:
            branches:
              only:
                - master