#!/bin/bash
# quit if something within the script fails
set -beEu -o pipefail
source `which qaConfig.bash`

################################
#
# 06/07/10 Mary Goldman
#
# Script to make sure that tables in public genome-mysql server are not corrupted.
# Does this by selecting * from table limit 5 (data from limit 1 is stored in metaDb
# table automatically made by mysql databases).
#  
################################

if [ $# -ne 1 ] 
then
  echo -e "
	checks genome-mysql servers for corrupted tables\n
	Note: Due to the bash configurations in this 
	script, if mysql encounters an error, the script
	will immediately exit and will not check the 
	rest of the tables in database. 
	   usage: $(basename $0) database\n" >&2
  exit 1
else
  db="$1"
fi

# make sure this is a valid database name
if ! mysql --user=genome --host=genome-mysql.soe.ucsc.edu -A -Ne "show databases" | grep -qw $db
then
  echo -e "\nERROR: database $db not found.\n" >&2
  exit 1
fi

tableList=$(mysql --user=genome --host=genome-mysql.soe.ucsc.edu -A -Ne "show tables" $db)

# for each table in list do a select * limit 5.
# Want to limit output or else the query would take forever. However,
# can't do limit 1 since the first row of every table is stored in
# the metadata and thus, mysql will not actually touch the table
# if you do a select statement with a limit 1. Thus, we do a limit 5.
# Throw away result of select statement and allow MySQL errors to be reported.
# Also, genome-mysql is actually two hosts.  Check both.
for ip in $(host genome-mysql.soe.ucsc.edu | awk '/has address/ {print $4}')
do
  for table in $tableList
  do
    mysql --user=genome --host=$ip -A -Ne "select * from $table limit 5" \
        $db > /dev/null

#PUT THIS BACK IF SD MACHINES COME BACK  mysql --user=genome --host=hgfs-sd.soe.ucsc.edu -A -Ne "select * from $table limit 5" \
#      $db > /dev/null
  done
done
exit 0
