#!/usr/bin/env bash
[ "$1" == "" ] && exec echo "Usage: $0 <DB_TYPE: ACCOUNTDB / GAMEDB / WORLDDB / SOCIETYDB>"
source $HOME/.gamerc

usage() {
    exec echo "Usage: $0 <DB_TYPE: ACCOUNTDB / GAMEDB / WORLDDB / SOCIETYDB>"
}

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

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

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

[[ $# -lt 1 ]] && usage

DB_TYPE=$1

DB_LIST=($(generate_mapping))
COUNT_DB_LIST=${#DB_LIST[@]}
ACTUAL_CNT=0 
#echo "DB_LIST: ${DB_LIST[@]}"
#echo "COUNT DB_LIST: ${COUNT_DB_LIST}"

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
    DB_CHECK_DIRECTORY="$HOME/common-TEST/db"
else
    DB_CHECK_DIRECTORY="$HOME/common/db"
fi

case ${DB_TYPE} in
    ACCOUNTDB*)
        EXPECTED_CNT=1
        EXPECTED_VERSION=$(grep -E '^version ' ${DB_CHECK_DIRECTORY}/account_schema_alter | tail -n 1 | awk -F" " '{print $2}')
        ;;
    GAMEDB*)
        EXPECTED_CNT=$COUNT_DB_LIST
        EXPECTED_VERSION=$(grep -E '^version ' ${DB_CHECK_DIRECTORY}/game_schema_alter | tail -n 1 | awk -F" " '{print $2}' )
        ;;
    WORLDDB*)
        EXPECTED_CNT=$COUNT_DB_LIST
        EXPECTED_VERSION=$(grep -E '^version ' ${DB_CHECK_DIRECTORY}/world_schema_alter | tail -n 1 | awk -F" " '{print $2}' | dos2unix)
        EXPECTED_VERSION=$(grep -E '^version ' "${DB_CHECK_DIRECTORY}/world_schema_alter" | tail -n 1 | awk '{print $2}' | tr -d '\r')
        ;;
    SOCIETYDB*)
        EXPECTED_CNT=$COUNT_DB_LIST
        EXPECTED_VERSION=$(grep -E '^version ' ${DB_CHECK_DIRECTORY}/society_schema_alter | tail -n 1 | awk -F" " '{print $2}')
        ;;
	*)
		echo "ERROR: DB_TYPE must be 'ACCOUNTDB' or 'GAMEDB' or 'WORLDDB' or 'SOCIEYTDB'"; usage
		;;
esac	

for db in "${DB_LIST[@]}"; do
    #echo "DB_NAME: ${db}"
    CHECKED_VERSION=$(psql -U postgres ${db} -c "COPY (SELECT schema_version FROM configuration) TO STDOUT CSV;")
    #echo "EXPECTED_VERSION: X${EXPECTED_VERSION}X"
    #echo "CHECKED_VERSION: X${CHECKED_VERSION}X"
    if [ "${EXPECTED_VERSION}" == "${CHECKED_VERSION}" ]; 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
