#!/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
		
#FIX_SERVER_LISTS=("MissionServer1" "ZoneServer101" "ZoneServer102")
FIX_SERVER_TOTAL_NUM=${#FIX_SERVER_LISTS[@]}
echo "FIX_SERVER_TOTAL_NUM => $FIX_SERVER_TOTAL_NUM"

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
		STRING_CHECK=$($HOME/bin/get_all_server_cpu_affinity_into_arr)
		read -ra ARRAY_CHECK <<< "$STRING_CHECK"
		if [ ${#ARRAY_CHECK[@]} -eq 0 ]; then
			if [ "${FIX_CPU_ID_TOTAL_NUM}" -ge "${FIX_SERVER_TOTAL_NUM}" ]; then
				LOOP_FIX_SERVER_LISTS=("${FIX_SERVER_LISTS[@]:0:${FIX_SERVER_TOTAL_NUM}}")
			else
				LOOP_FIX_SERVER_LISTS=("${FIX_SERVER_LISTS[@]:0:${FIX_CPU_ID_TOTAL_NUM}}")
			fi

			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}
				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', '$server', ${PROCESS_ID}, '${FIX_CPU_ID_LISTS[$idx]}');\""
			done
		fi
	else
		echo 'Not set isolcpus on grub and reboot'
	fi
else
	echo 'Not Enable parameter ${ENABLE_FIX_CPU_FOR_GAMESERVERS}.'
fi
