version: 2.1

defaults: &defaults
  working_directory: ~/shuttlerock_shared_config
  docker:
    - image: cimg/ruby:3.0.2-node
      auth:
        username: $DOCKERHUB_USERNAME
        password: $DOCKERHUB_PASSWORD

orbs:
  jira: circleci/jira@1.3.0

jobs:
  build:
    <<: *defaults

    parallelism: 1

    steps:
      - checkout
      - run:
          name: install dependencies
          command: |
            bundle config set path 'vendor/bundle'
            bundle install --jobs=4 --retry=3
      - save_cache:
          paths:
            - ./vendor/bundle
          key: v1-dependencies-{{ checksum "Gemfile.lock" }}
      - run:
          name: Step for RSpec
          command: |
            mkdir /tmp/test-results
            TEST_FILES="$(circleci tests glob "spec/**/*_spec.rb" | circleci tests split --split-by=timings)"

            bundle exec rspec --format progress \
                            --out /tmp/test-results/rspec.xml \
                            --format progress \
                            $TEST_FILES
      # collect reports
      - store_test_results:
          path: /tmp/test-results
      - store_artifacts:
          path: /tmp/test-results
          destination: test-results
      - jira/notify

  deploy_rubygems:
    <<: *defaults
    steps:
      - checkout
      - run:
          name: Setup Rubygems
          command: bash .circleci/setup-rubygems.sh
      - run:
          name: Publish to Rubygems
          command: |
            gem build shuttlerock_shared_config.gemspec
            gem push "$(ls | grep shuttlerock_shared_config-)"
      - jira/notify

  deploy_npm:
    <<: *defaults
    steps:
      - checkout
      - run:
          name: Setup NPM
          command: bash .circleci/setup-npm.sh
      - run:
          name: Publish to NPM
          command: npm publish
      - jira/notify

workflows:
  version: 2
  build-n-deploy:
    jobs:
      - build:
          context:
            - docker-hub-creds
            - jira-integration
          filters:  # required since `deploy` has tag filters AND requires `build`
            tags:
              only: /.*/
      - deploy_rubygems:
          context:
            - docker-hub-creds
            - jira-integration
          requires:
            - build
          filters:
            tags:
              only: /^v.*/
            branches:
              ignore: /.*/
      - deploy_npm:
          context:
            - docker-hub-creds
            - jira-integration
          requires:
            - build
          filters:
            tags:
              only: /^v.*/
            branches:
              ignore: /.*/
