variables:
  # Version de git utilisée
  GIT_VERSION: v2.30.1

  # Branche cible pour les PDF (modifiable via CI/CD variables)
  PDF_BRANCH: "pdf"

  FILE_NAMES: 2024-2025-rapport-csi 2024-2025-presentation-csi

build_tex:
  stage: build
  image: registry.gitlab.com/islandoftex/images/texlive:latest
  script:
    - |
      for FILE_NAME in $FILE_NAMES
      do
        echo "Compiling ${FILE_NAME}"
        pdflatex --shell-escape ${FILE_NAME}.tex
        if test -f ${FILE_NAME}.bcf; then
          echo "Found ${FILE_NAME}.bcf, running biber"
          biber ${FILE_NAME}
        fi
        pdflatex --shell-escape ${FILE_NAME}.tex
      done
  after_script:
    - |
      for FILE_NAME in $FILE_NAMES
      do
        echo "============================================"
        cat ${FILE_NAME}.log
        echo "============================================"
      done

  artifacts:
    paths:
      - "*.pdf"
deploy:
  stage: deploy
  image:
    name: alpine/git:${GIT_VERSION}
    entrypoint: [""]

  before_script:
    # Clone le repo dans un dossier temporaire
    - git clone "https://${GITLAB_USERNAME}:${GITLAB_TOKEN}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git" "${CI_COMMIT_SHA}"

    # Configure l’identité git
    - git config --global user.email "${GIT_USER_EMAIL:-$GITLAB_USER_EMAIL}"
    - git config --global user.name "${GIT_USER_NAME:-$GITLAB_USER_NAME}"

  script:
    # Déplace les PDFs compilés dans le repo cloné
    - mv *.pdf "${CI_COMMIT_SHA}/"
    - cd "${CI_COMMIT_SHA}"

    # Crée une branche orpheline (vierge, sans historique ni fichiers)
    - git checkout --orphan "${PDF_BRANCH}"
    - git reset --hard

    # Ajoute uniquement les PDF
    - git add -f *.pdf

    # Vérifie s’il y a des changements et push
    - |
      CHANGES=$(git status --porcelain | wc -l)
      if [ "$CHANGES" -gt "0" ]; then
        git commit -m "${COMMIT_MESSAGE:-Updating PDF files}"
        git push --force origin "${PDF_BRANCH}" -o ci.skip
      else
        echo "No PDF changes to commit"
      fi