#
# Copyright (C) 2022 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0

# NOTE: Because this worklow is using secrets, it cannot run directly on a pull-request workflow, which is running in the context of the forked repository.

name: Publish pull request content on netlify

on:
  workflow_run:
    workflows:
      - 'pr-check'
    types:
      - completed

jobs:
  publish:
    name: Publish content of the website pull request on netlify
    runs-on: ubuntu-24.04
    steps:
      - name: Download website content artifact
        uses: dawidd6/action-download-artifact@v7
        with:
          workflow: ${{ github.event.workflow_run.workflow_id }}
          name: website-content
          path: content
          allow_forks: true

      - name: Publish preview netlify
        uses: netlify/actions/cli@master
        id: netlify-publish
        with:
          args: deploy --dir=content/website/build --functions=functions
        env:
          NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}

      - name: 'Update status of Pull Request'
        uses: actions/github-script@v7
        with:
          script: |
            const { repo: { owner, repo } } = context;
            const netlifyUrl = '${{ steps.netlify-publish.outputs.NETLIFY_URL }}';
            const fs = require('node:fs');
            let sha = await fs.promises.readFile('content/PR_SHA', 'utf8');
            sha = sha?.trim();
            if (sha && sha.length !== 40) {
              throw new Error('Invalid PR_SHA');
            }
            // ensure it's a valid sha and contains only hex characters (no space, dot, etc) else exit
            if (sha && !sha.match(/^[0-9a-fA-F]+$/)) {
              throw new Error('Invalid PR_SHA');
            }
            await github.rest.repos.createCommitStatus({ owner, repo, sha, state: "success", target_url: netlifyUrl, description: "See pull request website online", context: "netlify"})
