name: Push Staging Plugin on PR Close

on:
  pull_request:
    types:
      - closed
  workflow_dispatch:
    inputs:
      pr_number:
        description: "PR number to test with"
        required: true
        type: string
      pr_merged:
        description: "Simulate merged PR"
        required: true
        type: boolean
        default: true

jobs:
  push-staging:
    if: (github.event_name == 'pull_request' && github.event.pull_request.merged == true) || (github.event_name == 'workflow_dispatch' && inputs.pr_merged == true)
    runs-on: ubuntu-latest
    permissions:
      contents: read
      actions: read
    steps:
      - name: Set Timezone
        uses: szenius/set-timezone@v2.0
        with:
          timezoneLinux: "America/Los_Angeles"

      - name: Set PR number
        id: pr_number
        run: |
          if [ "${{ github.event_name }}" == "pull_request" ]; then
            echo "pr_number=${{ github.event.pull_request.number }}" >> $GITHUB_OUTPUT
          else
            echo "pr_number=${{ inputs.pr_number }}" >> $GITHUB_OUTPUT
          fi

      - name: Download artifact
        uses: dawidd6/action-download-artifact@v11
        with:
          name_is_regexp: true
          name: unraid-plugin-.*
          path: connect-files
          pr: ${{ steps.pr_number.outputs.pr_number }}
          workflow_conclusion: success
          workflow_search: true
          search_artifacts: true

      - name: Update Downloaded Staging Plugin to New Date
        run: |
          # Find the .plg file in the downloaded artifact
          plgfile=$(find connect-files -name "*.plg" -type f | head -1)
          if [ ! -f "$plgfile" ]; then
            echo "ERROR: .plg file not found in connect-files/"
            ls -la connect-files/
            exit 1
          fi

          echo "Found plugin file: $plgfile"
          version=$(date +"%Y.%m.%d.%H%M")
          sed -i -E "s#(<!ENTITY version \").*(\">)#\1${version}\2#g" "${plgfile}" || exit 1
                
          # Change the plugin url to point to staging
          url="https://preview.dl.unraid.net/unraid-api/dynamix.unraid.net.plg"
          sed -i -E "s#(<!ENTITY plugin_url \").*?(\">)#\1${url}\2#g" "${plgfile}" || exit 1
          cat "${plgfile}"
          mkdir -p pr-release
          mv "${plgfile}" pr-release/dynamix.unraid.net.plg

      - name: Upload to Cloudflare
        uses: jakejarvis/s3-sync-action@v0.5.1
        env:
          AWS_S3_ENDPOINT: ${{ secrets.CF_ENDPOINT }}
          AWS_S3_BUCKET: ${{ secrets.CF_BUCKET_PREVIEW }}
          AWS_ACCESS_KEY_ID: ${{ secrets.CF_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.CF_SECRET_ACCESS_KEY }}
          AWS_REGION: "auto"
          SOURCE_DIR: pr-release
          DEST_DIR: unraid-api/tag/PR${{ steps.pr_number.outputs.pr_number }}
