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

steps:
  - name: build_tex
    image: registry.gitlab.com/islandoftex/images/texlive:latest
    commands:
      - pdflatex --shell-escape cv.tex
      - pdflatex --shell-escape cv.tex # Exécuter deux fois pour gérer les références croisées
      - cat cv.log
    when:
      - path:
          include: ["*.tex", ".woodpecker/*.yaml", ".woodpecker/*.yml"]
        event: [push, pull_request, manual, cron]

  - name: deploy
    image: *GIT_VERSION
    commands:
      - mkdir -p ~/.ssh
      - chmod 700 ~/.ssh
      # Create the SSH key file
      - echo "$SSH_KEY" > ~/.ssh/id_ed25519
      - chmod 600 ~/.ssh/id_ed25519
      - ssh-keyscan -t ed25519  -p 2220 git.polarolouis.fr >> ~/.ssh/known_hosts
      - chmod 644 ~/.ssh/known_hosts
      # Set the GIT_SSH_COMMAND to use the SSH key
      - export GIT_SSH_COMMAND="ssh -i ~/.ssh/id_ed25519 -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"
      # Clone the repository via SSH inside a new directory
      - git clone "${CI_REPO_CLONE_SSH_URL}" repo

      # Set the displayed user with the commits that are about to be made
      - git config --global user.email "${CI_COMMIT_AUTHOR_EMAIL:-CI_COMMIT_AUTHOR_EMAIL}"
      - git config --global user.name "${CI_COMMIT_AUTHOR:-CI Bot}"

      # Go to the repository directory
      - cd repo
      - pwd
      - ls

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


      # Move the generated PDF to the repository directory
      - mv ../cv.pdf ./

      # Add all generated files to Git
      - git add -f cv.pdf
      - git status
      - |-
        # Show the status of files that are about to be created, updated or deleted
        git status

        # Commit all changes
        git commit -m "Built pdf for ${CI_COMMIT_SHA:0:8} [CI SKIP]"

        # Update the repository and make sure to skip the pipeline create for this commit
        git push origin "$PDF_BRANCH" -o ci.skip
    environment:
      SSH_KEY:
        from_secret: SSH-KEY
      PDF_BRANCH: "pdf"

    when:
      - path:
          include: ["*.tex", ".woodpecker/*.yaml", ".woodpecker/*.yml"]
        event: [push, pull_request, manual, cron]
