variables:
  # https://hub.docker.com/r/alpine/git/tags
  GIT_VERSION: v2.30.1

.git:push:
  after_script:
    # Go to the new directory
    - cd "${CI_COMMIT_SHA}"

    - pwd

    - ls

    # Add all generated files to Git
    - git add README.md

    - git status

    - |-
      # Check if we have modifications to commit
      CHANGES=$(git status --porcelain | wc -l)

      if [ "$CHANGES" -gt "0" ]; then
        # Show the status of files that are about to be created, updated or deleted
        git status

        # Commit all changes
        git commit -m "${COMMIT_MESSAGE}"

        # Update the repository and make sure to skip the pipeline create for this commit
        git push origin "${CI_DEFAULT_BRANCH}" -o ci.skip
      fi
  before_script:
    # Clone the repository via HTTPS inside a new directory
    - git clone "https://${GITLAB_USERNAME}:${GITLAB_TOKEN}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git" "${CI_COMMIT_SHA}"

    # Set the displayed user with the commits that are about to be made
    - git config --global user.email "${GIT_USER_EMAIL:-$GITLAB_USER_EMAIL}"
    - git config --global user.name "${GIT_USER_NAME:-$GITLAB_USER_NAME}"
  image:
    entrypoint: [""]
    name: alpine/git:${GIT_VERSION}
  stage: deploy

stages:
  - render
  - deploy

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

deploy:
  extends: .git:push
  script:
    - mv README.md "${CI_COMMIT_SHA}/"
  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
