#!/usr/bin/env bash
[ "$1" == "" ] && exec echo "Usage: $0 <ACTION:open/close>"
source $HOME/.gamerc

ACTION=$1

is_related() {
    local teststr=$1
    # 確保變數存在且非空（避免未設定時直接迴圈空跑）
    [[ -n "${HOSTS_SERVERS_RELATED:-}" ]] || return 1

    for prefix in $HOSTS_SERVERS_RELATED; do
        # 重要：把變數用引號包起來，但 * 不要包（保留萬用字元）
        if [[ $teststr == "$prefix"* ]]; then
            return 0
        fi
    done
    return 1
}

generate_mapping() {
	local RETURN_SERVER_LIST_ARR=()
	IFS='_' read -ra parts <<< "$HOST_NAME"
	for server in "${parts[@]}"; do
		if is_related "$server"; then
			mapping=$(hostname2server $server);
			if [ -n "${mapping+x}" ] && [ -n "$mapping" ]; then
				RETURN_SERVER_LIST_ARR+=(${mapping})
			fi
		fi
	done
	echo "${RETURN_SERVER_LIST_ARR[@]}"
}

SERVER_LIST=($(generate_mapping))
COUNT_SERVER_LIST=${#SERVER_LIST[@]}
#echo "SERVER_LIST: ${SERVER_LIST[@]}"
#echo "COUNT SERVER_LIST: ${COUNT_SERVER_LIST}"

case ${ACTION} in
	open)
		EXPECTED_CNT=$COUNT_SERVER_LIST
		ACTUAL_CNT=0
		#echo "open => ${SERVER_LIST[@]}"
		for server in "${SERVER_LIST[@]}"; do
			#CHECKED=$(pgrep -f ${server})
			#CHECKED=$(pgrep -x ${server})
            re_server=$(printf '%s' "$server" | sed -e 's/[.[\()*^$+?{|\\]/\\&/g')
            CHECKED=$(pgrep -a -f '(^|[[:space:]])\./'"$re_server"'($|[[:space:]])' | awk '{print $1}')
			#echo "${server} => ${CHECKED}"
			if [ -n "${CHECKED+x}" ] && [ -n "$CHECKED" ]; then	
				(( ACTUAL_CNT++ ))
			fi
		done

		#echo "EXPECTED_CNT: ${EXPECTED_CNT}"
		#echo "ACTUAL_CNT: ${ACTUAL_CNT}"
		if [ "${EXPECTED_CNT}" -eq "${ACTUAL_CNT}" ]; then
			echo "1"
		else
			echo "-1"
		fi
		;;
	close)
		EXPECTED_CNT=0
		ACTUAL_CNT=$COUNT_SERVER_LIST
		#echo "close => ${SERVER_LIST[@]}"
		for server in "${SERVER_LIST[@]}"; do
			#CHECKED=$(pgrep -f ${server})
			#CHECKED=$(pgrep -x ${server})
            re_server=$(printf '%s' "$server" | sed -e 's/[.[\()*^$+?{|\\]/\\&/g')
            CHECKED=$(pgrep -a -f '(^|[[:space:]])\./'"$re_server"'($|[[:space:]])' | awk '{print $1}')
			#echo "${server} => ${CHECKED}"
			if [ -z "$CHECKED" ]; then	
				(( ACTUAL_CNT-- ))
			fi
		done
		#echo "EXPECTED_CNT: ${EXPECTED_CNT}"
		#echo "ACTUAL_CNT: ${ACTUAL_CNT}"
		if [ "${EXPECTED_CNT}" -eq "${ACTUAL_CNT}" ]; then
			echo "0"
		else
			echo "-1"
		fi
		;;
	*)
		echo "Unknown parameter"
		;;
esac	
