# Copyright (C) 2025 The Android Open Source Project
#
# 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.

# This workflow requires that pull requests coming from a forked repo (hence
# non-googlers) have 2 reviews from Google organization members.

name: Enforce 2 Google org member reviews for fork PRs

on:
  pull_request_target:
    types: [opened, synchronize, labeled, edited, auto_merge_enabled, auto_merge_disabled]

permissions:
  pull-requests: read

concurrency:
  group: enforce-reviews-pr-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  enforce-reviews:
    # Deliberately run on GitHub's ubuntu-latest pool as it's faster for small
    # job like this.
    runs-on: ubuntu-latest
    steps:
      - name: Check if PR is from a fork
        id: fork_check
        shell: bash
        run: |
          echo "is_fork=${{ github.event.pull_request.head.repo.full_name != github.repository }}" >> $GITHUB_ENV
          echo "Triggered by: ${{ github.event_name }}, ${{ github.event.review.state }} by ${{ github.event.review.user.login }}"

      - name: Check Google org member reviews
        if: env.is_fork == 'true'
        shell: bash
        run: |
          PR_NUMBER=${{ github.event.pull_request.number }}
          REPO="${{ github.repository }}"
          LATEST_SHA="${{ github.event.pull_request.head.sha }}"

          REVIEWS=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            "https://api.github.com/repos/$REPO/pulls/$PR_NUMBER/reviews")

          # Get unique reviewers who approved the latest commit
          REVIEWERS=$(echo "$REVIEWS" | jq -r --arg sha "$LATEST_SHA" '
          [group_by(.user.login)[] | last] |
          map(select(
            .state == "APPROVED" and
            .commit_id == $sha
          )) |
          .[].user.login')

          echo "Reviewers who approved latest commit ($LATEST_SHA):"
          echo "$REVIEWERS"
          echo ""

          # Check Google org membership for each reviewer
          GOOGLE_ORG_COUNT=0
          GOOGLE_ORG_MEMBERS=""

          for reviewer in $REVIEWERS; do
            echo "Checking Google org membership for: $reviewer"

            # Check if user is a member of Google organization
            HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
              -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
              "https://api.github.com/organizations/1342004/public_members/$reviewer")

            if [ "$HTTP_STATUS" = "204" ]; then
              echo "✅ $reviewer is a Google org member"
              GOOGLE_ORG_COUNT=$((GOOGLE_ORG_COUNT + 1))
              GOOGLE_ORG_MEMBERS="$GOOGLE_ORG_MEMBERS $reviewer"
            elif [ "$HTTP_STATUS" = "404" ]; then
              echo "❌ $reviewer is not a Google org member (or membership is private)"
            else
              echo "⚠️  Unknown status ($HTTP_STATUS) for $reviewer"
            fi
          done

          echo ""
          echo "Google org member approvals for latest commit: $GOOGLE_ORG_COUNT"
          echo "Google org members who approved: $GOOGLE_ORG_MEMBERS"

          if [ "$GOOGLE_ORG_COUNT" -lt 2 ]; then
            echo ""
            echo "❌ PR from fork requires 2 Google organization member approvals on the latest commit."
            echo ""
            echo "Reviews API Output for debug:"
            echo "---------------------------------------------------------------"
            echo "$REVIEWS"
            echo "---------------------------------------------------------------"
            exit 1
          fi

          echo "✅ PR has sufficient Google org member approvals ($GOOGLE_ORG_COUNT >= 2)"
