#!/bin/bash

TEMP_FILE="/tmp/hosts"
cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep 'GAMEDB' > ${TEMP_FILE}
while IFS= read -r line
do
        echo "LINE: $line"
        NF=$(echo ${line} | awk -F" " '{print NF}')
        echo "Number of fields: $NF"
        GAMEDB_IP=$(echo ${line} | awk -F" " '{print $1}')
        for((i=2; i<=$NF; i++)); do
                FIELD=$(echo ${line} | awk -F" " "{print \$$i}")
                if [[ $FIELD == "GAMEDB"* ]]; then
                        SET_NUM=$(echo $FIELD | sed 's/GAMEDB//')
                        echo "SET$SET_NUM: $GAMEDB_IP"

                        ssh -n GAMEDB$SET_NUM -o StrictHostKeyChecking=no "[ ! -d $HOME/servers$SET_NUM/ ] && mkdir -p $HOME/servers$SET_NUM/" < /dev/null
                        LOCAL_FILE=$(ssh -n GAMEDB$SET_NUM -o StrictHostKeyChecking=no "[ -f $HOME/servers$SET_NUM/.serverstatus.sql ] && echo '1' || echo '0'" < /dev/null)
                        if [[ "$LOCAL_FILE" == "0" ]]; then
                                REMOTE_FILE=$(ssh -n ACCOUNTDB -o StrictHostKeyChecking=no "[ -f $HOME/servers1/MissionServer1/.serverstatus.sql ] && echo '1' || echo '0'" < /dev/null)
                                if [[ "$REMOTE_FILE" == "1" ]]; then
                                        ssh -n GAMEDB$SET_NUM -o StrictHostKeyChecking=no "scp -o StrictHostKeyChecking=no ACCOUNTDB:$HOME/servers1/MissionServer1/.serverstatus.sql $HOME/servers$SET_NUM/" < /dev/null
                                fi                                        
                        fi

                        RESULT=$(ssh -n GAMEDB$SET_NUM -o StrictHostKeyChecking=no "psql -h GAMEDB$SET_NUM -U spiritking UG1DB$SET_NUM -c \"COPY (SELECT COUNT(*) FROM serverstatus WHERE id = -2 AND name = 'MissionServer1') TO STDOUT CSV\"" < /dev/null)
                        if [[ "$RESULT" == "0" ]]; then
                                ssh -n GAMEDB$SET_NUM -o StrictHostKeyChecking=no "psql -h GAMEDB$SET_NUM -U spiritking UG1DB$SET_NUM -f $HOME/servers$SET_NUM/.serverstatus.sql" < /dev/null
                        fi
                fi
        done
        echo
done < "${TEMP_FILE}"