name: Deploy React portfolio

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    container:
      image: node:20-bookworm
      volumes:
        - /home/deploy/.ssh:/root/.ssh:ro
    
    steps:
      - name: Install SSH client
        run: |
          apt-get update && apt-get install -y openssh-client rsync
          
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install deps
        run: npm ci
        
      - name: Build
        run: npm run build

      - name: Check SSH keys
        run: |
          echo "=== SSH keys available? ==="
          ls -la /root/.ssh/

      - name: Deploy to web server
        run: |
          # determine build output dir
          if [ -d build ]; then DIR=build
          elif [ -d dist ]; then DIR=dist
          else
            echo "❌ No build output directory found" >&2
            ls -la
            exit 1
          fi
          echo "Using build dir: $DIR"

          # deploy
          tar czf portfolio.tar.gz -C "$DIR" .
          scp -i /root/.ssh/deploy_to_web -o StrictHostKeyChecking=accept-new portfolio.tar.gz deploy@91.98.34.152:/tmp/
          ssh -i /root/.ssh/deploy_to_web -o StrictHostKeyChecking=accept-new deploy@91.98.34.152 "\
            sudo rm -rf /var/www/louisemard.dev/* && \
            sudo tar xzf /tmp/portfolio.tar.gz -C /var/www/louisemard.dev/ && \
            sudo rm /tmp/portfolio.tar.gz && \
            sudo chown -R deploy:www-data /var/www/louisemard.dev && \
            sudo chmod -R 775 /var/www/louisemard.dev && \
            sudo systemctl reload nginx"
          
      - name: Success
        run: echo "✅ Déployé sur https://louisemard.dev"