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

if ! command -v taskset &> /dev/null; then
	# Check OS Debian to do do the security settings
	OS_DISTRO=$(cat /etc/os-release | grep ^ID= | sed 's/ID=//;s/"//g')
	if [ "${OS_DISTRO}" == "debian" -o "${OS_DISTRO}" == "ubuntu" ]; then
		sudo apt-get update
		sudo apt-get install -y util-linux
	elif [ "${OS_DISTRO}" == "centos" -o "${OS_DISTRO}" == "fedora" ]; then
		sudo yum -y install util-linux
	fi
fi
		
if [ "${ENABLE_FIX_CPU_FOR_GAMESERVERS}" == "1" ]; then
	FIX_CPU_ID_STR=$(cat /proc/cmdline | tr ' ' '\n' | grep isolcpus | awk -F"=" '{print $2}')
	IFS="," read -ra FIX_CPU_ID_LISTS <<< "${FIX_CPU_ID_STR}"
	FIX_CPU_ID_TOTAL_NUM=${#FIX_CPU_ID_LISTS[@]}

	echo "FIX_CPU_ID_TOTAL_NUM => $FIX_CPU_ID_TOTAL_NUM"
	if [ "${FIX_CPU_ID_TOTAL_NUM}" -gt 0 ]; then
		LOOP_FIX_SERVER_LISTS=$(ps -eo pid,pcpu,comm --sort=-pcpu | grep Server | awk '{print $3}' | head -n ${FIX_CPU_ID_TOTAL_NUM})

		for idx in ${!LOOP_FIX_SERVER_LISTS[@]}; do
			server=${LOOP_FIX_SERVER_LISTS[$idx]}
			while ! ps -ef | egrep -v 'grep|rsync' | grep "./${server}" | awk -F" " '{print $2}' > /dev/null; do
				sleep 1 # Check every second
			done

			PROCESS_ID=$(ps -ef | egrep -v 'grep|rsync' | grep "./${server}" | awk -F" " '{print $2}')

			echo "$server ( ${PROCESS_ID} ) => ${FIX_CPU_ID_LISTS[$idx]} ( $idx )"
			taskset -cp ${FIX_CPU_ID_LISTS[$idx]} ${PROCESS_ID}
		done

		#LOOP_FIX_SERVER_LISTS=$(ps -eo pid,pcpu,comm --sort=-pcpu | grep Server | awk '{print $3}' | head -n ${FIX_CPU_ID_TOTAL_NUM})

		#for idx in ${!LOOP_FIX_SERVER_LISTS[@]}; do
		#	server=${LOOP_FIX_SERVER_LISTS[$idx]}
		#	pid=$(ps -ef | egrep -v 'grep|rsync' | grep "./${server}" | awk -F" " '{print $2}')
		#	echo "$server ( ${PROCESS_ID} ) => ${FIX_CPU_ID_LISTS[$idx]} ( $idx )"
		#	taskset -cp ${FIX_CPU_ID_LISTS[$idx]} ${PROCESS_ID}
		#done
	else
		echo 'Not set isolcpus on grub and reboot'
	fi
else
	echo 'Not Enable parameter ${ENABLE_FIX_CPU_FOR_GAMESERVERS}.'
fi
