stages:
  - render
  - commit

check_readme_changes:
  stage: render
  image: ghcr.io/quarto-dev/quarto:latest
  script:
    - |
      apt update && apt install -y git
      if git diff --name-only $CI_COMMIT_BEFORE_SHA $CI_COMMIT_SHA | grep -q 'README.qmd'; then
        echo "README.qmd modifié, rendu en cours."
        quarto render README.qmd
      else
        echo "Aucune modification de README.qmd, arrêt de la pipeline."
        exit 0
      fi
  artifacts:
    paths:
      - README.md
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      when: always
    - if: '$CI_PIPELINE_SOURCE == "push"'
      changes:
        paths:
          - README.qmd
      when: always

commit_and_push:
  stage: commit
  image: alpine:latest
  before_script:
    - apk add --no-cache git
  script:
    - |
      if git diff --name-only $CI_COMMIT_BEFORE_SHA $CI_COMMIT_SHA | grep -q 'README.qmd'; then
        git config --global user.email "ci@example.com"
        git config --global user.name "CI Bot"
        git add README.md
        git commit -m "[ci skip]: maj auto du README.md après rendu Quarto"
        git push origin HEAD:$CI_COMMIT_REF_NAME
      else
        echo "Aucun commit/push nécessaire."
      fi
  dependencies:
    - check_readme_changes
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      when: always
    - if: '$CI_PIPELINE_SOURCE == "push"'
      changes:
        paths:
          - README.qmd
      when: always
