#!/bin/bash

# Checks Kafka logs for unsupported warning patterns
# Only specified warnings are allowed, all others should trigger failure

allowed_patterns=(
  # Enabling share groups (KIP-932) requires "share" in group.coordinator.rebalance.protocols
  # on cp-kafka 8.3.0 (Kafka 4.x). That mechanism is deprecated in favour of the share.version
  # feature flag (Kafka 5.0), but is still functionally required to enable share groups in this
  # version, so the broker logs this deprecation warning on every startup. Expected here.
  "group.coordinator.rebalance.protocols. is deprecated"
  "Performing controller activation"
  "registered with feature metadata.version"
  "Replayed TopicRecord for"
  "Replayed PartitionRecord for"
  "Previous leader None and previous leader epoch"
  "Creating new"
  "Unloaded transaction metadata"
  "closing connection"
  "sent a heartbeat request but received error REQUEST_TIMED_OUT"
  "Topic '__consumer_offsets' already exists"
)

# Get all warnings
warnings=$(docker logs --since=0 kafka | grep "] WARN ")
exit_code=0

while IFS= read -r line; do
  allowed=0
  for pattern in "${allowed_patterns[@]}"; do
    if echo "$line" | grep -q "$pattern"; then
      allowed=1
      break
    fi
  done

  if [ $allowed -eq 0 ]; then
    echo "Unexpected warning found:"
    echo "$line"
    exit_code=1
  fi
done <<< "$warnings"

exit $exit_code
