name: My Gatsby Deployment pipeline
run-name: ${{ gitea.actor }} is deploying this page to production.

on:
  push:
    branches:
      - master  

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Repository auschecken
        uses: actions/checkout@v3

      - name: Node.js einrichten
        uses: actions/setup-node@v3
        with:
          node-version: 18

      - name: Clear node_modules and package-lock
        run: |
          rm -rf node_modules
          rm -f package-lock.json

      - name: Install Dependencies
        run: |
          npm install --legacy-peer-deps --force
          npm install -g gatsby-cli

      - name: Clean Gatsby cache
        run: |
          gatsby clean

      - name: Build Gatsby Site
        run: |
          gatsby build
        env:
          NODE_ENV: production
          CI: true

      - name: Check build output
        run: |
          if [ ! -d "public" ]; then
            echo "Build failed - public directory not found"
            exit 1
          fi

      - name: Upload build artifacts
        uses: actions/upload-artifact@v3
        with:
          name: gatsby-build
          path: public/

  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Download build artifacts
        uses: actions/download-artifact@v3
        with:
          name: gatsby-build
          path: public

      - name: Install SSH key
        uses: shimataro/ssh-key-action@v2
        with:
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          known_hosts: ${{ secrets.SSH_KNOWN_HOSTS }}

      - name: Deploy to web server
        env:
          DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }}
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
        run: |
          rsync -avz -e "ssh -p 2266" \
            --exclude='mailadmin/' \
            --exclude='postfixadmin/' \
            --exclude='roundcube/' \
            public/ \
            $DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH


      - name: Verify deployment
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
          DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }}
        run: |
          ssh $DEPLOY_USER@$DEPLOY_HOST "test -d $DEPLOY_PATH && echo 'Deployment successful' || (echo 'Deployment failed' && exit 1)"
