name: Déploiement PROD

on:
  push:
    branches:
      - main

  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Récupérer le dépôt
        uses: https://github.com/actions/checkout@v4

      - name: Installer les outils
        run: |
          apt-get update
          apt-get install -y rsync openssh-client

      - name: Configurer SSH VPS
        env:
          SSH_PRIVATE_KEY: ${{ secrets.VPS_SSH_KEY }}
          VPS_HOST: ${{ vars.VPS_HOST }}
          VPS_PORT: ${{ vars.VPS_PORT }}
        run: |
          mkdir -p ~/.ssh
          printf '%s\n' "$SSH_PRIVATE_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519

          ssh-keyscan \
            -p "$VPS_PORT" \
            "$VPS_HOST" \
            >> ~/.ssh/known_hosts

          chmod 600 ~/.ssh/known_hosts

      - name: Vérifier la destination PROD
        env:
          VPS_HOST: ${{ vars.VPS_HOST }}
          VPS_PORT: ${{ vars.VPS_PORT }}
          VPS_USER: ${{ vars.VPS_USER }}
          VPS_PATH: ${{ vars.VPS_PATH }}
        run: |
          ssh \
            -p "$VPS_PORT" \
            -i ~/.ssh/id_ed25519 \
            -o IdentitiesOnly=yes \
            "$VPS_USER@$VPS_HOST" \
            "test -d '$VPS_PATH' && test -w '$VPS_PATH'"

      - name: Déployer sur le VPS
        env:
          VPS_HOST: ${{ vars.VPS_HOST }}
          VPS_PORT: ${{ vars.VPS_PORT }}
          VPS_USER: ${{ vars.VPS_USER }}
          VPS_PATH: ${{ vars.VPS_PATH }}
        run: |
          rsync -rz \
            --no-perms \
            --no-owner \
            --no-group \
            --omit-dir-times \
            --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r \
            --exclude=".git/" \
            --exclude=".gitea/" \
            --exclude=".env" \
            --exclude="uploads/" \
            --exclude="logs/" \
            --exclude="storage/" \
            -e "ssh -p $VPS_PORT -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes" \
            ./ \
            "$VPS_USER@$VPS_HOST:$VPS_PATH/"