#!/bin/bash -e
usage='checkMetaDb directory metaDb db0 ...'

UNAME_N=`uname -n`
UNAME_N=${UNAME_N/.soe.ucsc.edu/}

if [ $# -lt 3 ] ; then
    echo "wrong # args: $usage" >&2
    exit 1
fi

directory="$1"; shift
metaDb="$1"; shift
dbs="$@"

# check if a database exists, print note and return non-zero if it doesn't
dbExists() {
    local db="$1"
    local dbChk=$(hgsql -Ne 'show databases like "'$db'"')
    if [ -z "$dbChk" ] ; then
        echo "Note: database $db does not exist, skipping"
        return 1
    else
        return 0
    fi
}

# chck metaDb for a database
checkMetaDb() {
    local db="$1"
    local dbpath=$(ls -1 -d */$db)
    local org=$(echo $dbpath | sed -e 's/\/.*//')
    local metaDir=$dbpath/metaDb/$directory

    if test \! -d $metaDir
    then
        return;
    fi

    touch $metaDir/metaDb
    echo hgsqlTableDate $db $metaDb $metaDir/metaDb 
    hgsqlTableDate $db $metaDb $metaDir/metaDb || rm $metaDir/metaDb 

    # makefile will call makeMetaDb if file list is newer than table
    (cd $metaDir && make DB=$db TABLE=$metaDb)
    rm -f $metaDir/metaDb
}

# load for all specified databases
for db in $dbs ; do
    if dbExists $db ; then
        checkMetaDb $db
    fi
done

