name: Deploy to FTP (OVH)

on:
  push:
    branches: [ main ]
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Validate FTP configuration
        env:
          OVH_FTP_HOST: ${{ secrets.OVH_FTP_HOST }}
          OVH_FTP_USER: ${{ secrets.OVH_FTP_USER }}
          OVH_FTP_PASSWORD: ${{ secrets.OVH_FTP_PASSWORD }}
          OVH_FTP_PORT: ${{ secrets.OVH_FTP_PORT }}
          OVH_FTP_REMOTE_PATH_NEW: ${{ secrets.OVH_FTP_REMOTE_PATH_NEW }}
        run: |
          if [ -z "$OVH_FTP_HOST" ] || [ "$OVH_FTP_HOST" = "ftp.example.com" ]; then
            echo "❌ Error: OVH_FTP_HOST is not configured"
            echo "Add OVH_FTP_HOST to repository Secrets"
            exit 1
          fi
          echo "✅ FTP configuration looks set"

      - name: Install lftp
        run: sudo apt-get update && sudo apt-get install -y lftp

      - name: Deploy via lftp mirror
        env:
          OVH_FTP_HOST: ${{ secrets.OVH_FTP_HOST }}
          OVH_FTP_USER: ${{ secrets.OVH_FTP_USER }}
          OVH_FTP_PASSWORD: ${{ secrets.OVH_FTP_PASSWORD }}
          OVH_FTP_PORT: ${{ secrets.OVH_FTP_PORT }}
          OVH_FTP_REMOTE_PATH_NEW: ${{ secrets.OVH_FTP_REMOTE_PATH_NEW }}
        run: |
          REMOTE_PATH="${OVH_FTP_REMOTE_PATH_NEW:-/www/cats}"
          PORT_OPT="${OVH_FTP_PORT:-21}"
          echo "📤 Deploying to $OVH_FTP_HOST:$PORT_OPT$REMOTE_PATH"
          lftp -u "${OVH_FTP_USER},${OVH_FTP_PASSWORD}" -p "$PORT_OPT" "$OVH_FTP_HOST" <<EOF
          set ssl:verify-certificate no
          # create remote dir if missing and mirror local -> remote
          mkdir -p "$REMOTE_PATH"
          mirror -R --parallel=2 --verbose --delete --exclude-glob .git --exclude-glob node_modules --exclude-glob .github ./ "$REMOTE_PATH"
          bye
          EOF

      - name: Notify success
        if: success()
        run: echo "✅ Deployment finished"

      - name: Notify failure
        if: failure()
        run: |
          echo "❌ Deployment failed - check logs"
          exit 1
