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

################################
#  
#  09-26-2007
#  Ann Zweig
#
#  findLevel
#  find out which level in the trackDb directory
#  a track is on, and which level the corresponding
#  .html file is on.
#
#  02-25-2010
#  Brooke Rhead
#  Changed to a bash script to simplify dealing with stderr
#  and stdout.
#
################################

db=""
tableName=""
currDir=""
error="no"

# get arguments or print usage
if [ $# -ne 2 ] 
then
  echo -e "
  searches trackDb hierarchy for your table and corresponding .html file
  also returns the value of the priority and visibility entries
  and the .ra file location for each\n
    usage:  database tableName\n" >&2
  exit 1
else
  db="$1"
  tableName="$2"
fi

# check for kent source dir at $USER root
if ! [ -d ~/kent/src/hg/makeDb/trackDb/ ]
then
  echo -e "\n  ERROR: `basename $0` presumes you have the kent source
  source tree in your home dir, in a dir called \"kent\"\n" >&2
  exit 1
fi

# make sure this is a valid database name
if ! hgsql -Ne "show databases" | grep -qw $db
then
  echo -e "\nERROR: database $db not found.  Try running on hgwdev?\n" >&2
  exit 1
fi

echo

###########################################
# find the level of the associated .html file
# start at the assembly level
cd ~/kent/src/hg/makeDb/trackDb/*/$db
currDir=""

if [ -e $tableName.html ]
then # the .html file is found at the assembly level
  currDir=`pwd -P`
else
  cd ..
  if [ -e $tableName.html ]
  then # the .html file is found at the organism level
    currDir=`pwd -P`
  else
    cd ..
    if [ -e $tableName.html ]
    then # the .html file is found at the top level
      currDir=`pwd -P`
    fi
  fi
fi

if [ "$currDir" == "" ]
then
  echo -e " * the $tableName.html file does not exist at any level\n"
else
  echo -e " * html file: $currDir/$tableName.html\n"
fi

###########################################
# find the trackDb.ra entry (using tdbQuery)
# the tdbQuery default is -release=alpha
echo " * trackDb:"
alpha=`tdbQuery "select track,release,priority,visibility,filePos from \
     $db where track='$tableName'" 2> /dev/null` || error=yes

beta=`tdbQuery -release=beta "select track,release,priority,visibility,filePos from \
        $db where track='$tableName'" 2> /dev/null` || error=yes

public=`tdbQuery -release=public "select track,release,priority,visibility,filePos from \
       $db where track='$tableName'" 2> /dev/null` || error=yes

# always print "alpha"; only print beta or public if they differ from alpha
echo -e "$alpha\n"
if [ "$alpha" != "$beta" ]
then
  echo -e "$beta\n"
fi
if [ "$alpha" != "$public" ] && [ "$beta" != "$public" ] 
then
  echo -e "$public\n"
fi

# if tdbQuery is only giving errors, variables will be empty and nothing printed
if [ "$error" = "yes" ]
then
  echo -e "\nERROR: tdbQuery returned errors\n" >&2
  exit 1
fi

exit 0
