name: '[CI/CD] CI Pipeline'
on: # rebuild any PRs and main branch changes
  pull_request_target:
    types:
      - synchronize
      - labeled
    branches:
      - main
      - bitnami:main
permissions: {}
# Avoid concurrency over the same PR
concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
jobs:
  get-containers:
    runs-on: ubuntu-latest
    name: Get modified containers
    permissions:
      pull-requests: read
    if: |
      github.event.pull_request.state != 'closed' &&
      (
        contains(github.event.pull_request.labels.*.name, 'verify') || (github.event.action == 'labeled' && github.event.label.name == 'verify')
      )
    outputs:
      result: ${{ steps.get-containers.outputs.result }}
      containers: ${{ steps.get-containers.outputs.containers }}
      dockerfiles: ${{ steps.get-containers.outputs.dockerfiles }}
    steps:
      - id: get-containers
        name: Get modified containers
        env:
          PULL_REQUEST_NUMBER: "${{ github.event.pull_request.number }}"
          GITHUB_TOKEN: "${{ github.token }}"
        run: |
          files_changed="$(gh api --paginate /repos/${GITHUB_REPOSITORY}/pulls/${PULL_REQUEST_NUMBER}/files | jq -r '.[] | .filename')"
          # Adding || true to avoid "Process exited with code 1" errors
          flavors=($(echo "$files_changed" | xargs dirname | grep -o "^bitnami/[^/]*/[^/]*/[^/]*" | sort | uniq || true))
          assets=($(echo "$files_changed" | xargs dirname | sed -nr "s|bitnami/([^/]*)/.*|\1|p" | sort | uniq || true))
          non_readme_files=$(echo "$files_changed" | grep -vc "\.md" || true)
          dockerfiles=($(echo "$files_changed" | grep -oE ".*/Dockerfile$" | sort | uniq || true))

          if [[ "$non_readme_files" -le "0" ]]; then
            # The only changes are .md files -> SKIP
            echo "result=skip" >> $GITHUB_OUTPUT
          elif [[ "${#assets[@]}" -ge "5" ]]; then
            echo "Maximun number of assets reached. You are currently modifying: ${assets[@]}"
            echo "result=skip" >> $GITHUB_OUTPUT
          else
            containers_json=$(printf "%s\n" "${flavors[@]}" | jq -R . | jq -cs .)
            dockerfiles_json=$(printf "%s\n" "${dockerfiles[@]}" | jq -R . | jq -cs .)
            echo "result=ok" >> $GITHUB_OUTPUT
            echo "containers=${containers_json}" >> $GITHUB_OUTPUT
            echo "dockerfiles=${dockerfiles_json}" >> $GITHUB_OUTPUT
          fi
  license-headers-linter:
    runs-on: ubuntu-latest
    name: License Headers Linter
    permissions:
      contents: read
      pull-requests: write
    needs: get-containers
    if: |
      needs.get-containers.outputs.result == 'ok'
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
        name: Checkout Repository
        with:
          ref: ${{ github.event.pull_request.head.ref }}
          repository: ${{ github.event.pull_request.head.repo.full_name }}
      - id: get-modified-files
        name: 'Get modified files'
        env:
          DOCKERFILES: "${{ needs.get-containers.outputs.dockerfiles }}"
        run: |
          if [[ -n "${DOCKERFILES}" ]]; then
            # Overwrite configuration file to analyze only changed dockerfiles
            yq -i '. | .header.paths=env(DOCKERFILES)' .licenserc.yaml
            echo "result=success" >> $GITHUB_OUTPUT
          else
            echo "result=skip" >> $GITHUB_OUTPUT
          fi
      - name: Check license Headers
        uses: apache/skywalking-eyes/header@61275cc80d0798a405cb070f7d3a8aaf7cf2c2c1
        if: ${{ steps.get-modified-files.outputs.result == 'success' }}
  auto-pr-review:
    runs-on: ubuntu-latest
    name: Reviewal for automated PRs
    permissions:
      pull-requests: write
    needs:
      - license-headers-linter
    # This job will be executed when the PR was created by bitnami-bot and it has the 'auto-merge' label
    if: |
      contains(github.event.pull_request.labels.*.name, 'auto-merge') &&
      github.event.pull_request.user.login == 'bitnami-bot'
    steps:
      # Approve the CI's PR automatically, as it has been tested in our internal pipeline already
      # Approved by the 'github-actions' user; a PR can't be approved by its author
      - name: PR Approval
        uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd
        with:
          result-encoding: string
          retries: 3
          script: |
            github.rest.pulls.createReview({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: context.issue.number,
              event: 'APPROVE',
            });
      - name: Merge
        id: merge
        uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd
        with:
          result-encoding: string
          retries: 3
          # Necessary to trigger CD workflows
          github-token: ${{ secrets.BITNAMI_BOT_TOKEN }}
          script: |
            github.rest.pulls.merge({
              pull_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              merge_method: 'squash'
            })
      # If the merge process did not succeed,
      # post a comment on the PR and assign a maintainer agent to review it
      - name: Manual review required
        if: ${{ always() && steps.merge.outcome != 'success' }}
        uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd
        env:
          BODY: |
            There has been an error during the automated release process. Manual revision is now required.
            Please check the related [action_run#${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for more information.
        with:
          retries: 3
          script: |
            const {BODY} = process.env
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `${BODY}`
            })
