#!/bin/bash
source $HOME/.gamerc

SQL_QUERY="SELECT * FROM match_node_stream ORDER BY node_id;"

if [ ! -z "$1" ]; then
  UPPER_HOSTNAME=$(echo $1 | tr [a-z] [A-Z])
  for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep -i "${UPPER_HOSTNAME}" | awk -F" " '{print $1}'); do
    IFS="_" read -ra SERVERNAME <<< $(print_servername ${ip})
    for name in "${SERVERNAME[@]}"; do
      if [[ "$name" == *GAMEDB* ]]; then
        print_servername ${ip} | colorize yellow
        set_id=$(echo ${name} | sed 's/GAMEDB//');
        ssh ${ip} "psql -U postgres ${GAME_DB_NAME}${set_id} -c \"${SQL_QUERY}\""
      fi
    done
  done
else
  for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep 'GAMEDB' | awk -F" " '{print $1}'); do
    IFS="_" read -ra SERVERNAME <<< $(print_servername ${ip})
    for name in "${SERVERNAME[@]}"; do
      if [[ "$name" == *GAMEDB* ]]; then
        print_servername ${ip} | colorize yellow
        set_id=$(echo ${name} | sed 's/GAMEDB//');
        ssh ${ip} "psql -U postgres ${GAME_DB_NAME}${set_id} -c \"${SQL_QUERY}\""
      fi
    done
  done
fi
