version: 2.1

workflows:
  version: 2
  ci:
    jobs:
      - build_and_test:
          filters:
            branches:
              ignore:
                - gh-pages
      - deploy:
          filters:
            branches:
              ignore:
                - gh-pages
          requires:
            - build_and_test

commands:
  install_dependencies:
    description: "Install dependencies with smart caching"
    parameters:
      image:
        type: string
      version:
        type: string
    steps:
      - restore_cache:
          keys:
            - &yarn_key yarn-<< parameters.image >>-<< parameters.version >>-{{ checksum "package.json" }}
            - yarn-<< parameters.image >>-<< parameters.version >>
      - run: yarn install --frozen-lockfile
      - save_cache:
          paths:
            - ~/.cache
            - node_modules
          key: *yarn_key

jobs:
  build_and_test:
    docker:
      - image: cypress/base:14.16.0
    working_directory: ~/repo
    steps:
      - checkout
      - install_dependencies:
          image: "cypress"
          version: "14"
      - run: yarn lint
      - run: yarn test --runInBand
      - run:
          command: yarn start
          background: true
      - run: yarn run wait-on http://localhost:6060 && yarn cypress run
  deploy:
    docker:
      - image: cimg/node:14.18
    working_directory: ~/repo
    steps:
      - checkout
      - install_dependencies:
          image: "node"
          version: "14"
      - run: |
          git config user.email "ci-deployment@mavenlink"
          git config user.name "CI Deployment"
      - add_ssh_keys:
          fingerprints:
            - "79:26:19:57:4e:1a:59:64:ec:bb:b7:76:e2:5f:7c:ad"
      - run:
          name: Compile and deploy Github pages
          command: |
            yarn build
            git checkout gh-pages
            git pull
            rm -rf $CIRCLE_BRANCH
            mkdir -p $CIRCLE_BRANCH
            mv -v build/* $CIRCLE_BRANCH
            git add .
            git diff-index --quiet HEAD || git commit -m 'Update Github pages for $CIRCLE_BRANCH'
            git push origin gh-pages
      - run: echo https://mavenlink.github.io/design-system/$CIRCLE_BRANCH/
      - run: ls $CIRCLE_BRANCH
