#!/bin/bash
set -u

# THIS SCRIPT FOR DEBUGGING AND TESTING ONLY

DEFAULT_STATEMENT="SELECT 1"

function print_usage()
{
    cat << EOF
$(basename "$0")[:<sql_statement>] -- Run SQL Statement

    <sql_statement> : an arbitrary SQLite statement

    Output defined by <sql_statement>.

    This report accepts and executes an arbitrary SQL statement.
    It is mostly for debugging/testing.  If no <sql_statement> is
    given, the statement ${DEFAULT_STATEMENT} is executed.
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 ###


SQL=${2:-${DEFAULT_STATEMENT}}

${RUN_SQLITE} << EOF

${SQL}
;
EOF
