name: Deploy to Server - nur geaenderte Dateien

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 2

      - name: Geaenderte Dateien ermitteln
        id: changed
        run: |
          git diff --name-only --diff-filter=ACM HEAD~1 HEAD \
            | grep -vE '^(\.git|\.github|node_modules|vendor|storage)' \
            > changed_files.txt || true

          echo "=== Geaenderte Dateien ==="
          cat changed_files.txt

          if [ -s changed_files.txt ]; then
            echo "has_changes=true" >> $GITHUB_OUTPUT
          else
            echo "has_changes=false" >> $GITHUB_OUTPUT
          fi

      - name: lftp installieren
        if: steps.changed.outputs.has_changes == 'true'
        run: sudo apt-get install -y lftp

      - name: Geaenderte Dateien hochladen
        if: steps.changed.outputs.has_changes == 'true'
        env:
          FTP_SERVER: ${{ secrets.FTP_SERVER }}
          FTP_USERNAME: ${{ secrets.FTP_USERNAME }}
          FTP_PASSWORD: ${{ secrets.FTP_PASSWORD }}
        run: |
          while read file; do
            if [ -f "$file" ]; then
              echo "Uploading: $file"
              lftp -u "$FTP_USERNAME,$FTP_PASSWORD" \
                sftp://$FTP_SERVER -e "
                  set sftp:connect-program 'ssh -o StrictHostKeyChecking=no';
                  set cmd:fail-exit no;
                  mkdir -p $(dirname $file);
                  set cmd:fail-exit yes;
                  put -O $(dirname $file) $file;
                  quit"
            fi
          done < changed_files.txt
          echo "=== Deploy abgeschlossen ==="

      - name: Keine Aenderungen
        if: steps.changed.outputs.has_changes == 'false'
        run: echo "Keine deploybaren Dateien geaendert."
