#!/bin/bash -e
usage='buildTrix trixName metaDbName path_to_cv.ra outputPath ${DBS}'

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

trixName="$1"; shift
metaDbName="$1" ; shift
cvRaPath="$1" ; shift
outPath="$1" ; shift
dbs="$@"

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

buildDbTrix() {
    local db="$1"
    local trixName="$2"
    local metaDbName="$3"
    local cvRaPath="$4"
    local outPath="$5"
    local tmpFile=`mktemp`;
    makeTrackIndex $db $metaDbName $cvRaPath > $tmpFile;
    if test -s $tmpFile; then
        ixIxx $tmpFile $outPath/${db}_${trixName}.ix $outPath/${db}_${trixName}.ixx
    fi
    rm -f $tmpFile 
}

for db in $dbs ; do
    if dbExists $db ; then
        buildDbTrix $db $trixName $metaDbName $cvRaPath $outPath
    fi
done
