#!/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

# Only sqlite3's exit code and stdout decide the result. Its stderr can hold
# messages that are not sqlite's, such as "File /run/dlconf.dat open error"
# printed early in the boot, so it is only printed as the reason of a failure.
check_result="`sqlite3 "$db" "pragma integrity_check" 2>/dev/null`"
if [ $? -ne 0 ]; then
	# sqlite3 could not run the check; print its error as the reason.
	sqlite3 "$db" "pragma integrity_check" 2>&1 >/dev/null
	exit 1
fi
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"`"
	query="SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '$name' COLLATE NOCASE"
	found="`sqlite3 "$db" "$query" 2>/dev/null`"
	if [ $? -ne 0 ]; then
		sqlite3 "$db" "$query" 2>&1 >/dev/null
		exit 1
	fi
	if [ -z "$found" ]; then
		echo "table $table is missing"
		exit 1
	fi
done

exit 0
