#!/bin/bash
source $HOME/.gamerc

process_name=$1
process_id=$(ps -eo pid,pcpu,comm --sort=-pcpu | grep ${process_name} | awk '{print $1}')

# Validate PID
if [[ -z "$process_id" || ! "$process_id" =~ ^[0-9]+$ ]]; then
  echo "Usage: $0 <process_id>"
  exit 1
fi

# Get total number of CPUs
#total_cpus=$(nproc)
total_cpus=$(grep -c ^processor /proc/cpuinfo)

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

#echo "๐ํด Found isolcpus=[$isolcpus_raw] in /proc/cmdline"
#echo "๐ง ํท  Total CPUs: $total_cpus"

# Function to expand CPU ranges
expand_cpus() {
  echo "$1" | tr ',' '\n' | while read part; do
    if [[ "$part" == *-* ]]; then
      seq "${part%-*}" "${part#*-}"
    else
      echo "$part"
    fi
  done
}

# Expand isolated CPUs
isolated_array=()
if [[ -n "$isolcpus_raw" ]]; then
  mapfile -t isolated_array < <(expand_cpus "$isolcpus_raw")
fi

#echo "๐งชํทช Isolated CPUs: ${isolated_array[*]}"

# Build non-isolated list
non_isolated_list=()
for ((i = 0; i < total_cpus; i++)); do
  skip=false
  for iso in "${isolated_array[@]}"; do
    if [[ "$i" -eq "$iso" ]]; then
      skip=true
      break
    fi
  done
  if ! $skip; then
    non_isolated_list+=("$i")
  fi
done

# Check and apply
if [[ ${#non_isolated_list[@]} -eq 0 ]]; then
  echo "โ No available non-isolated CPUs to assign. Check isolcpus or system config."
  exit 1
fi

cpu_range=$(IFS=,; echo "${non_isolated_list[*]}")
#echo "โ Assigning PID $process_id to non-isolated CPUs: $cpu_range"
taskset -cp "$cpu_range" "$process_id"
if [ "$HOST_NAME" == "TEST" -o "$HOST_NAME" == "SUB" -o "$HOST_NAME" == "SUBMIT" -o "$HOST_NAME" == "DATA" -o "$HOST_NAME" == "DLC" -o "$HOST_NAME" == "TIME1" -o "$HOST_NAME" == "MEDIA" ] ; then
	ENVIRONMENT="TEST"
else
	ENVIRONMENT="LIVE"
fi
ssh CTRL "psql -U postgres WebTool -c \"INSERT INTO monitor_server_cpu_affinity (environment, host_name, process_name, process_id, cpu_id) VALUES ('$ENVIRONMENT', '$HOST_NAME', '$process_name', $process_id, '$cpu_range');\""
