name: Deploy Webzine
run-name: Deploy to production by @${{ github.actor }}

on: [push]

jobs:
  # ─────────────────────────────────────────────
  # DÉPLOIEMENT — Build et démarrage sur le serveur
  # ─────────────────────────────────────────────
  deploy-production:
    name: Deploy to Production
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      # Écriture de la clé SSH
      - name: Setup SSH key
        run: |
          mkdir -p ~/.ssh
          printf '%s\n' "${{ secrets.PROD_SSH_KEY }}" > ~/.ssh/id_prod
          chmod 600 ~/.ssh/id_prod
          ssh-keyscan -p ${{ secrets.PROD_SSH_PORT || 22 }} ${{ secrets.PROD_HOST }} >> ~/.ssh/known_hosts 2>/dev/null

      # Compression du code source et transfert vers le serveur
      - name: Upload source to server
        run: |
          tar --exclude='.git' --exclude='*.user' -czf /tmp/webzine-src.tar.gz .
          scp -i ~/.ssh/id_prod \
              -P ${{ secrets.PROD_SSH_PORT || 22 }} \
              -o StrictHostKeyChecking=no \
              /tmp/webzine-src.tar.gz \
              ${{ secrets.PROD_USER }}@${{ secrets.PROD_HOST }}:/tmp/webzine-src.tar.gz

      # Build et redémarrage du conteneur directement sur le serveur
      - name: Build and deploy on PRODUCTION server
        run: |
          ssh -i ~/.ssh/id_prod \
              -p ${{ secrets.PROD_SSH_PORT || 22 }} \
              -o StrictHostKeyChecking=no \
              ${{ secrets.PROD_USER }}@${{ secrets.PROD_HOST }} << 'ENDSSH'
            set -e

            echo "=== [PROD] Extraction des sources ==="
            mkdir -p /opt/webzine/prod/src
            tar -xzf /tmp/webzine-src.tar.gz -C /opt/webzine/prod/src/
            rm /tmp/webzine-src.tar.gz

            echo "=== [PROD] Construction de l'image ==="
            docker build \
              -t webzine:latest \
              -f /opt/webzine/prod/src/Webzine.WebApplication/Dockerfile \
              /opt/webzine/prod/src/

            echo "=== [PROD] Arrêt de l'ancien conteneur ==="
            docker stop webzine-prod 2>/dev/null || true
            docker rm   webzine-prod 2>/dev/null || true

            echo "=== [PROD] Démarrage du nouveau conteneur ==="
            docker run -d \
              --name webzine-prod \
              --restart unless-stopped \
              -p 80:8080 \
              -p 443:8081 \
              -v /opt/webzine/prod/data:/app/Data \
              -v /opt/webzine/prod/logs:/Logs \
              -e ASPNETCORE_ENVIRONMENT=Production \
              webzine:latest

            echo "=== [PROD] Nettoyage des anciennes images ==="
            docker image prune -f

            echo "=== [PROD] Déploiement terminé ==="
          ENDSSH