name: CD Develop Pipeline
on:
  pull_request:
    branches:
      - develop
    types: [closed]

jobs:
  build-plugin-zip:
    name: Build ${{ github.event.repository.name }} plugin zip
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest
    steps:
      -   name: Clone source code
          uses: actions/checkout@v3

      -   name: Set up PHP
          uses: shivammathur/setup-php@v2
          with:
              php-version: 8.1

      -   name: Prepare plugin for zipping
          run: |
              rm -rf $(pwd)/.git
              rm -rf $(pwd)/.github

      -   name: Create plugin zip file
          run: zip -r $(pwd)/${{ github.event.repository.name }}.zip .

      -   name: Download Artifacts
          uses: actions/upload-artifact@v3
          with:
              name: ${{ github.event.repository.name }}
              path: /home/runner/work/${{ github.event.repository.name }}/${{ github.event.repository.name }}/${{ github.event.repository.name }}.zip
              if-no-files-found: error
  deploy-to-staging:
    name: Deploy ${{ github.event.repository.name }} to development cluster
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest
    steps:
      - name: Login using SSH, deploy and install plugin
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.STAGING_ENV_SSH_HOST }}
          username: ${{ secrets.STAGING_ENV_SSH_USER }}
          key: ${{ secrets.STAGING_ENV_SSH_KEY }}
          debug: true
          script: |
            cd ${{ secrets.STAGING_ENV_PATH }}custom/plugins/${{ github.event.repository.name }}
            git remote rm origin
            git remote add origin https://${{ secrets.STAGING_ENV_GITHUB_ACCESS_KEY }}@github.com/${{ github.repository }}
            git fetch origin
            git checkout develop
            git pull --rebase origin develop
            cd ${{ secrets.STAGING_ENV_PATH }}
            bin/console plugin:refresh
            bin/console plugin:update ${{ github.event.repository.name }}
            bin/console cache:clear