version: 2

defaults: &defaults
  docker:
    - image: circleci/ruby:2.4

workflows:
  version: 2
  validate:
    jobs:
      - validate_atomics

  generate-guids-and-docs:
    jobs:
      - generate_and_commit_guids_and_docs:
          filters:
            branches:
              only: master

jobs:
  validate_atomics:
    <<: *defaults
    steps:
      - checkout
      - add_ssh_keys

      - run:
          name: Validate the format of atomic tests against the spec
          command: |
            bin/validate-atomics.rb

  generate_and_commit_guids_and_docs:
    <<: *defaults
    steps:
      - checkout
      - add_ssh_keys

      - run:
          name: Generate and commit unique GUIDs for each atomic test
          command: |
            bin/generate-guids.rb

            echo ""
            echo ""
            git status
            echo ""
            echo ""
            git diff-index HEAD --

            if git diff-index --quiet HEAD -- ; then
              echo "Not committing GUID changes because there are no changes"
            else
              git config credential.helper 'cache --timeout=120'
              git config user.email "<email>"
              git config user.name "CircleCI Atomic Red Team GUID generator"

              git add atomics
              git commit -am "Generate GUIDs from job=$CIRCLE_JOB branch=$CIRCLE_BRANCH [skip ci]"
              git push -u origin $CIRCLE_BRANCH
            fi

      - run:
          name: Generate and commit nice markdown documents for atomics
          command: |
            bin/generate-atomic-docs.rb

            echo ""
            echo ""
            git status
            echo ""
            echo ""
            git diff-index HEAD --

            if git diff-index --quiet HEAD -- ; then
              echo "Not committing documentation because there are no changes"
            else
              git config credential.helper 'cache --timeout=120'
              git config user.email "<email>"
              git config user.name "CircleCI Atomic Red Team doc generator"

              git add atomics
              git commit -am "Generate docs from job=$CIRCLE_JOB branch=$CIRCLE_BRANCH [skip ci]"
              git push -u origin $CIRCLE_BRANCH
            fi
