#!/bin/bash
[  "$1" == "" ] && exec echo "Usage: $0 <sql query> <machine name>"
source $HOME/.gamerc

SQL_QUERY=$1

if [ ! -z "$2" ]; then
  UPPER_HOSTNAME=$(echo $2 | 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" == *WORLDDB* ]]; then
        print_servername ${ip} | colorize yellow
        set -f; echo ${SQL_QUERY}
        world_id=$(echo ${name} | sed 's/WORLDDB//');
        ssh ${ip} "psql -U postgres ${WORLD_DB_NAME}${world_id} -c \"${SQL_QUERY}\""
      fi
    done
  done
else
  for ip in $(cat /etc/hosts | sed -n '/\# PLEASE/,/# DO/p' | egrep 'WORLDDB' | awk -F" " '{print $1}'); do
    IFS="_" read -ra SERVERNAME <<< $(print_servername ${ip})
    for name in "${SERVERNAME[@]}"; do
      if [[ "$name" == *WORLDDB* ]]; then
        print_servername ${ip} | colorize yellow
        set -f; echo ${SQL_QUERY}
        world_id=$(echo ${name} | sed 's/WORLDDB//');
        ssh ${ip} "psql -U postgres ${WORLD_DB_NAME}${world_id} -c \"${SQL_QUERY}\""
      fi
    done
  done
fi
