#!/bin/sh

# check-integrity <db> [<table> ...]
#
# Checks that a database is usable: it exists, is not empty, passes sqlite's
# integrity_check pragma and has all the given tables.
#
# Exit codes:
#   0  the database is usable, nothing is printed
#   1  it is not usable, the reason is printed
#   2  wrong usage
#
# Nothing is logged here: the callers log the reason under their own tags.

PATH=/bin:/usr/bin:/sbin:/usr/sbin

if [ $# -lt 1 ]; then
	echo "Usage: $0 <db> [<table> ...]" >&2
	exit 2
fi

db="$1"
shift

if [ ! -e "$db" ]; then
	echo "database does not exist"
	exit 1
fi

if [ ! -s "$db" ]; then
	echo "database is empty"
	exit 1
fi

check_result="`sqlite3 "$db" "pragma integrity_check" 2>&1`"
if [ "$check_result" != "ok" ]; then
	echo "$check_result"
	exit 1
fi

for table in "$@"; do
	# Table names are case-insensitive in sqlite.
	name="`printf '%s' "$table" | sed -e "s/'/''/g"`"
	count="`sqlite3 "$db" "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = '$name' COLLATE NOCASE" 2>&1`"
	if [ "$count" = "0" ]; then
		echo "table $table is missing"
		exit 1
	fi
	if [ "$count" != "1" ]; then
		echo "$count"
		exit 1
	fi
done

exit 0
