#!/bin/bash

KEYWORD=$1
SCREEN_DIRECTORY="/var/run/screen/S-${USER}"
PROCESS_SHORT_NAME=$(echo ${KEYWORD}|sed 's/MissionServer/MS/;s/WorldServer/WS/;s/ZoneServer/ZS/')

for pid in $(ps -ef | egrep 'perf top|screen|create_screen_snapshot' | grep -v grep | grep ${PROCESS_SHORT_NAME} | awk -F" " '{print $2}'); do
	sudo kill -15 ${pid}
done

# 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" ]; then
	PERF_SECURITY_VAL=$(cat /proc/sys/kernel/perf_event_paranoid)
	if [ "${PERF_SECURITY_VAL}" -ne -1 ]; then
		sudo sh -c 'echo -1 > /proc/sys/kernel/perf_event_paranoid'
	fi
fi

PROCESS_ID=$(ps -ef | egrep "Mission|World|Zone"Server | grep '\./' | awk -F" " '{print $2","$NF}' | sed 's|./||' | sort -k2 | grep $KEYWORD | awk -F"," '{print $1}')
screen -S ${PROCESS_SHORT_NAME}.perf -d -m perf top -p ${PROCESS_ID}

SNAPSHOT_SOURCE_DIRECTORY="$HOME/perf.snapshot"
SNAPSHOT_DIRECTORY="${SNAPSHOT_SOURCE_DIRECTORY}/${PROCESS_SHORT_NAME}"
FILENAME="${PROCESS_SHORT_NAME}.perf"
echo "${KEYWORD} => ${PROCESS_SHORT_NAME}"

nohup $HOME/bin/create_screen_snapshot ${PROCESS_SHORT_NAME} ${SNAPSHOT_DIRECTORY} > /tmp/${FILENAME}.out 2> /tmp/${FILENAME}.err &
