#!/bin/sh

if [ -z "$VERNEUIL_CONFIG" ]; then
    if [ -e /etc/coronerd/coronerd.conf ]; then
	VERNEUIL_CONFIG="$(jq '.sqlite_replication | del(.replication_spooling_dir)' < /etc/coronerd/coronerd.conf)"
    else
	echo "VERNEUIL_CONFIG is not set and /etc/coronerd/coronerd.conf does not exist." >&2
	exit 1
    fi
    if [ "$VERNEUIL_CONFIG" = "null" ]; then
	echo "VERNEUIL_CONFIG is not set and no configuration could be generated from /etc/coronerd/coronerd.conf" >&2
	exit 1
    fi
    echo "Using VERNEUIL_CONFIG='$VERNEUIL_CONFIG'"
    export VERNEUIL_CONFIG
fi

if [ $# -eq 0 ]; then
    cat >&2 <<'__EOF__'
usage: verneuil_shell [--hostname <name>] --source-path <database-path.db>

Opens up an sqlite3 shell on a snapshot a database from a host.
The shell is preloaded with the sqlite protobuf support and
both crdb and coronerd protos.

If the VERNEUIL_CONFIG variable is not set, then a suitable one
is generated from /etc/coronerd/coronerd.conf.
__EOF__
    exit 1;
fi

# Start a sqlite3 shell with a read replica configured by the
# arguments, then load our protobuf extensions in the connection
# before dropping in the shell.
exec /opt/backtrace/bin/verneuilctl shell "$@" -- \
 -cmd ".load /opt/backtrace/lib/libsqlite_protobuf" \
 -cmd "select protobuf_load('/opt/backtrace/lib/libcrdb_proto.so');" \
 -cmd "select protobuf_load('/opt/backtrace/lib/libcoronerd_proto.so');"
