name: Invario review
on: [push, pull_request]
permissions: {}
jobs:
  review:
    if: >-
      (github.event_name == 'push' && github.event.created == false && github.event.deleted == false && startsWith(github.ref, 'refs/heads/'))
      || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository)
    permissions:
      contents: read
    runs-on: ubuntu-latest
    timeout-minutes: 55
    steps:
      - name: Request remote review
        env:
          INVARIO_URL: ${{ vars.INVARIO_URL }}
          INVARIO_CI_TOKEN: ${{ secrets.INVARIO_CI_TOKEN }}
          INVARIO_REVIEW_GATE: ${{ vars.INVARIO_REVIEW_GATE }}
          INVARIO_RECEIPTS_FILE: ${{ vars.INVARIO_RECEIPTS_FILE }}
          INVARIO_CI_RECEIPTS_TOKEN: ${{ secrets.INVARIO_CI_RECEIPTS_TOKEN }}
          BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }}
          HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.after }}
          GITHUB_COMPARE_TOKEN: ${{ github.token }}
          REQUEST_KEY: gh-${{ github.run_id }}-${{ github.run_attempt }}
        run: |
          set -eu
          if [ "${GITHUB_EVENT_NAME:-}" = pull_request ]; then
            comparison="$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/compare/$BASE_SHA...$HEAD_SHA?per_page=1"
            BASE_SHA=$(curl -fsS --max-time 30 --retry 2 -H "Authorization: Bearer $GITHUB_COMPARE_TOKEN" "$comparison" |
              jq -er '.merge_base_commit.sha | select(test("^[a-f0-9]{40}$"))')
          fi
          api="${INVARIO_URL%/}/v1/reviews"
          body=$(jq -nc --arg base "$BASE_SHA" --arg head "$HEAD_SHA" '{base:$base,head:$head}')
          if [ -n "${INVARIO_RECEIPTS_FILE:-}" ]; then
            body=$(printf '%s' "$body" | jq -ec --slurpfile evidence "$INVARIO_RECEIPTS_FILE" 'if ($evidence|length)==1 and ($evidence[0]|type)=="object" and $evidence[0].base==.base and $evidence[0].repositories.primary==.head then . + {receipts:$evidence[0]} else error("Expected one Invario receipt matching the requested commits") end')
          fi
          auth="Authorization: Bearer $INVARIO_CI_TOKEN"
          reply=$(printf '%s' "$body" | curl -fsS --max-time 30 --retry 2 -H "$auth" -H "Idempotency-Key: $REQUEST_KEY" \
            -H "X-Invario-Receipts-Token: ${INVARIO_CI_RECEIPTS_TOKEN:-}" \
            -H 'Content-Type: application/json' --data-binary @- "$api")
          id=$(printf '%s' "$reply" | jq -er '.id | select(test("^[0-9a-f]{32}$"))')
          echo "Invario review $id"
          while :; do
            reply=$(curl -fsS --max-time 30 --retry 2 -H "$auth" "$api/$id")
            status=$(printf '%s' "$reply" | jq -er '.status')
            case "$status" in
              completed)
                printf '%s' "$reply" | jq -e '.report' > invario-report.json
                verdict=$(jq -er '.review_verdict' invario-report.json)
                echo "$verdict"
                if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then
                  printf '## Invario review\n\n- Review `%s`\n- Verdict `%s`\n' "$id" "$verdict" >> "$GITHUB_STEP_SUMMARY"
                fi
                if [ "${INVARIO_REVIEW_GATE:-}" = 1 ]; then
                  if ! jq -e --arg base "$BASE_SHA" --arg head "$HEAD_SHA" \
                    '.base == $base and .repositories.primary == $head and .evidence.status == "complete" and .review_verdict == "pass"' \
                    invario-report.json >/dev/null; then
                    echo "Invario gate requires a complete passing report for $BASE_SHA..$HEAD_SHA" >&2
                    exit 1
                  fi
                fi
                break ;;
              queued|running) sleep 2 ;;
              *) echo "Review $id ended with status $status" >&2; exit 1 ;;
            esac
          done
