name: Check Maintenance Mode
description: Blocks CI when maintenance mode is active (issue #21065 is open), unless the PR has the bypass-maintenance label, or env SGLANG_PR_TEST_BYPASS_MAINTENANCE_ON_MAIN=true (PR Test workflow on main only). Merging non-CI-fix PRs is prohibited during maintenance mode; in severe cases, merge permissions may be revoked.

inputs:
  github-token:
    description: GitHub token for API access
    required: false
    default: ${{ github.token }}

runs:
  using: composite
  steps:
    - name: Check maintenance mode
      shell: bash
      env:
        GH_TOKEN: ${{ inputs.github-token }}
      run: |
        MAINTENANCE_ISSUE=21065
        REPO="${{ github.repository }}"
        PR_NUMBER="${{ github.event.pull_request.number }}"

        # PR Test workflow only: scheduled runs and runs on main (dispatch / workflow_call) set this env
        if [[ "${SGLANG_PR_TEST_BYPASS_MAINTENANCE_ON_MAIN:-}" == "true" ]]; then
          echo "✅ PR Test on main branch; bypassing maintenance gate."
          exit 0
        fi

        # Check if maintenance issue is open (fail-open: if API errors, allow CI to proceed)
        ISSUE_STATE=$(gh issue view "$MAINTENANCE_ISSUE" --repo "$REPO" --json state --jq '.state' 2>/dev/null || echo "UNKNOWN")

        if [[ "$ISSUE_STATE" != "OPEN" ]]; then
          echo "✅ Maintenance mode is OFF. Proceeding with CI."
          exit 0
        fi

        # For PRs, check if bypass-maintenance label is present
        if [[ -n "$PR_NUMBER" ]]; then
          HAS_BYPASS=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json labels --jq '[.labels[].name] | map(select(. == "bypass-maintenance")) | length' 2>/dev/null || echo "0")
          if [[ "$HAS_BYPASS" -gt 0 ]]; then
            echo "✅ PR #$PR_NUMBER has 'bypass-maintenance' label. Bypassing maintenance mode."
            exit 0
          fi
        fi

        MSG=$(printf "%s\n" \
          "## ⚠️ CI Maintenance Mode is Active" \
          "The CI infrastructure is currently under maintenance." \
          "All PR CI runs are paused until maintenance is complete." \
          "**Merging non-CI-fix PRs is prohibited during maintenance mode.** In severe cases, merge permissions may be revoked." \
          "You might also experience unexpected failures during this period." \
          "The team is working on the issue and will update the status as soon as possible." \
          "" \
          "What should you do?" \
          "- **Do NOT merge non-CI-fix PRs** until maintenance mode is lifted" \
          "- Check back later (~12 hours)" \
          "- Follow CI Maintenance Mode issue: https://github.com/$REPO/issues/$MAINTENANCE_ISSUE for status updates")

        echo "$MSG" >> "$GITHUB_STEP_SUMMARY"
        while IFS= read -r line; do
          echo "::error::$line"
        done <<< "$MSG"

        exit 1
