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

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

trixName="$1"; shift
metaDbName="$1" ; shift
cvRaPath="$1" ; shift
outMachine="$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"
    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
}

buildDbTrix() {
    local db="$1"
    local trixName="$2"
    local metaDbName="$3"
    local cvRaPath="$4"
    local outPath="$5"
    local tmpFile=`mktemp`;
    local tmpFile2=`mktemp`;
    local tmpFile3=`mktemp`;
    makeTrackIndex $db $metaDbName $cvRaPath > $tmpFile;
    if test -s $tmpFile; then
        ixIxx -maxWordLength=64 $tmpFile $tmpFile2 $tmpFile3
        # trixContextIndex makes the $db_$trixName.offsets and $db_$trixName.offsets.ixx files:
        trixContextIndex $tmpFile ${db}_${trixName}
        chmod 664  $tmpFile2 $tmpFile3 $tmpFile ${db}_${trixName}.offsets ${db}_${trixName}.offsets.ixx
        rsync -a $tmpFile2 $outMachine:$outPath/${db}_${trixName}.ix
        rsync -a $tmpFile3 $outMachine:$outPath/${db}_${trixName}.ixx
        # these three are for snippets on search pages:
        rsync -a $tmpFile $outMachine:$outPath/${db}_${trixName}.txt
        rsync -a ${db}_${trixName}.offsets $outMachine:$outPath/${db}_${trixName}.offsets
        rsync -a ${db}_${trixName}.offsets.ixx $outMachine:$outPath/${db}_${trixName}.offsets.ixx
        rm -f ${db}_${trixName}.offsets ${db}_${trixName}.offsets.ixx
    fi
    rm -f $tmpFile $tmpFile2 $tmpFile3
}

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