name: CD

on:
  workflow_run:
    workflows:
      - CI
    branches:
      - main
    types:
      - completed

jobs:
  deploy:
    name: Déploiement production
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    runs-on: ubuntu-latest
    steps:
      - name: 📥 Checkout
        uses: actions/checkout@v4

      - name: Configuration SSH
        run: |
          mkdir -p "$HOME/.ssh"
          echo "${{ secrets.DEPLOY_SSH_KEY }}" \
            > "$HOME/.ssh/id_ed25519"
          chmod 600 "$HOME/.ssh/id_ed25519"

          ssh-keyscan \
            -H "${{ secrets.DEPLOY_HOST }}" \
            >> "$HOME/.ssh/known_hosts"

      - name: 📄 Sync compose.prod.yaml
        run: |
          scp \
            -i "$HOME/.ssh/id_ed25519" \
            compose.prod.yaml \
            ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}:/data/docker/landing-server/docker-compose.yml

      - name: 🚀 Deploy Docker
        run: |
          ssh \
            -i "$HOME/.ssh/id_ed25519" \
            ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} << 'EOF'
          set -e

          echo "Projet"
          cd /data/docker/landing-server

          echo "Pull nouvelle image"
          docker compose pull

          echo "Redémarrage"
          docker compose up -d

          EOF
