#!/bin/bash
set -u

# THIS SCRIPT FOR DEBUGGING AND TESTING ONLY

function print_usage()
{
    cat << EOF
$(basename "$0")[:<sql_file>] -- Run SQL statement(s) from file

    <sql_file> : File with SQL statement(s)

    Output defined by <sql_file>.

    This report accepts and executes an arbitrary SQL statement.
    It is mostly for debugging/testing.  If no <sql_file> is given,
    or if the file does not exist, nothing is returned.
EOF
}

### BEGIN include inc_setup ###

EXIT_HELP=25
EXIT_DB=26
EXIT_NODATA=27

# Verify number of params
if [ $# -lt 1 ]
then
    print_usage ${BASH_SOURCE[0]}
    exit ${EXIT_HELP}
fi

# Set DB file
DATABASE="$1"

# Verify DB file exists
if [ ! -f "${DATABASE}" ]
then
    exit ${EXIT_DB}
fi

# Verify DB file contents
# The sqlite3 file format is defined at https://sqlite.org/fileformat.html
DB_FILE_HEADER=$(head -c 16 "$DATABASE" | tr '\0' '\n')
if [ "${DB_FILE_HEADER}" != "SQLite format 3" ]
then
    exit ${EXIT_DB}
fi

# Helper function for error messages
function echoerr() # accepts multiple args
{
    echo "$@" >&2
}

# Setup standard vars

# If we were run by nsys, the path to the preferred sqlite3 should have been
# passed as an env-var.  If not, hope the user has it in their path.
SQLITE3="${NSYS_STATS_SCRIPTS_SQLITE:-sqlite3}"
SQLITE3OPTS="-header -csv -readonly"

RUN_SQLITE="eval \"${SQLITE3}\" ${SQLITE3OPTS} \"${DATABASE}\""

### END include inc_setup ###


if [ $# -eq 1 ]
then
    echoerr "No SQL file given."
    exit ${EXIT_NODATA}
fi

SQLFILE="$2"

if [ ! -f "${SQLFILE}" ]
then
    echoerr "SQL file \"${SQLFILE}\" doesn't exist"
    exit ${EXIT_NODATA}
fi

${RUN_SQLITE} < "${SQLFILE}"
