#!/usr/bin/bash

export cgDirApp=${cgDirApp:-/opt/libre-bib}
export cgBin=$cgDirApp/bin

#--------------------
fUsage() {
    cat <<EOF

Usage:
    bib [-n] Cmds...
Options
    -n - no execute (if used, it must be the first option)
Cmds:
    edit-lo, edit-conf
    import-lo, export-lo, backup-lo, restore-lo, update-bib
    ref-new, ref-update, style-save, style-update
    status-bib, setup-bib, setup-db, connect, clean, clean-all, version, help

If nothing happenss, run 'bib status' to see if the commsnd has
already been run. To force a command to run remove the corresponging
date file from the $cgDirStatus

EOF
    exit 1
} # fUsage

# ========================================
if [[ $# -eq 0 || "$1" = "-h" ]]; then
    fUsage
fi
pParm=$*

if [[ ! -x $cgDirApp/bin/util.php ]]; then
    echo "Error: cgDirApp $cgDirApp is not correct [$LINENO]"
    exit 1
fi
if [[ ! -f $cgBin/bib-cmd.mak ]]; then
    echo "Error: cgBin $cgBin is not correct [$LINENO]"
    exit 1
fi

# App conf (assume this is only name=value)
. $cgDirApp/etc/conf.env

if [ ! -x conf.env ]; then
    read -p "Warning: Missing conf.env, copy it here now? "
    if [  "$REPLY" != "y" ] ; then
        exit 1
    fi
    make -f $cgBin/bib-cmd.mak conf.env
    echo 'Edit conf.env with your details. Uncomment the ones you'
    echo 'are changing, then run: bib setup-dir'
    exit 1
fi

if ! $cgBin/valid-conf.sh <./conf.env; then
    echo "Fix the above errors from valid-conf, then try again. [$LINENO]"
    exit 1
fi

. ./conf.env

make -f $cgBin/bib-cmd.mak -s setup-dir

if ! $cgBin/sanity-check.sh; then
    echo "Fix the above errors from saniy-check, then try again. [$LINENO]"
    exit 1
fi

tSilent="-s"
if [[ "$cgVerbose" == "true" ]]; then
    tSilent=""
fi
if [[ "$1" = "-n" ]]; then
    tSilent=""
fi

# Commands are executed with "make"
make -f $cgBin/bib-cmd.mak $tSilent $pParm

if [[ "${cgBuild:-false}" != "true" ]]; then
    if [[ $? -ne 0 ]]; then
        fUsage
    fi
fi
