version: 2.1

orbs:
  slack: circleci/slack@1.0.3

executors:
  nodejs_executor:
    docker:
      - image: node:10.15.0
    working_directory: /tmp/app

jobs:
  build:
    executor: nodejs_executor
    steps:
      - checkout
      - run: npm ci
      - persist_to_workspace:
          root: /tmp
          paths:
            - app
  lint:
    executor: nodejs_executor
    steps:
      - attach_workspace:
          at: /tmp
      - run: npm run lint

  publish:
    executor: nodejs_executor
    steps:
      - attach_workspace:
          at: /tmp
      - run:
          name: Add version number to environment variable
          command: |
            echo "export VERSION_NUMBER=$(node -p -e "require('./package.json').version")" >> $BASH_ENV
            echo VERSION_NUMBER=$VERSION_NUMBER
            source $BASH_ENV
      - run:
          name: Authenticate npm registry
          command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/.npmrc
      - run:
          name: Publish npm package
          command: npm publish /tmp/app
      - add_ssh_keys
      - run:
          name: Add github.com to ssh known_hosts
          command: ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
      - run:
          name: Sync to datum-sdk
          command: git push git@github.com:Datum/datum-sdk.git
      - slack/notify:
          message: 'datum-sdk@${VERSION_NUMBER} has been published'
          color: '#1cbf43'

publish_conditions: &publish_conditions
  requires:
    - build
  filters:
    branches:
      only:
        - master
        - feature/DAT-695-cicd

workflows:
  build_test_publish:
    jobs:
      - build
      - lint:
          requires:
            - build
      - slack/approval-notification:
          message: Step 'publish' in datum-sdk-internal is awaiting your approval.
          <<: *publish_conditions
      - approve_publish:
          type: approval
          <<: *publish_conditions
      - publish:
          requires:
            - approve_publish
