#!/bin/bash

PATTERN=$1

# Extract isolcpus CPU list from /proc/cmdline
isolated_cpus=$(grep -oP 'isolcpus=\K[^ ]+' /proc/cmdline)

# Convert ranges like 2-4 to list: 2 3 4
expand_cpus() {
  echo "$1" | tr ',' '\n' | while read part; do
    if [[ "$part" == *-* ]]; then
      seq "${part%-*}" "${part#*-}"
    else
      echo "$part"
    fi
  done
}

# Expand to an array of isolated CPU IDs
mapfile -t cpu_list < <(expand_cpus "$isolated_cpus")

output=()
# Process each PID and check affinity and name
for pid in $(ls /proc | grep -E '^[0-9]+$'); do
  [[ -r /proc/$pid/status ]] || continue
  cpus_allowed=$(grep '^Cpus_allowed_list:' /proc/$pid/status | awk '{print $2}')
  cmd=$(ps -p "$pid" -o comm= 2>/dev/null)

  # Skip if process name doesn't match *Server*
  [[ "$cmd" == "${PATTERN}" ]] || continue

  for cpu in "${cpu_list[@]}"; do
    # Check if the allowed CPU list includes this isolated CPU
    if echo "$cpus_allowed" | grep -qw "$cpu"; then
      echo $cpus_allowed
      break
    fi
  done
done
