#!/bin/bash

# Compare two sqlite databases schema
# intended to compare an operationnal database schema against what it would be like if
# just created with package's setup.

if [ $# -lt 2 ]; then
	echo "Usage: `basename $0` db1 db2"
	exit 1
fi

normalize_schema() {
	local dbfile="$1"
	for table in $(sqlite3 $dbfile "select name from sqlite_master where type='table' and name!='sqlite_sequence' order by name")
	do
		# Print table info
		# Note: table-valued functions for PRAGMA feature is only available for SQLite version >= 3.16.0 (2017-01-02).
		#sqlite3 $dbfile "select '$table', ti.name, ti.type, ti.\"notnull\", ti.dflt_value, ti.pk from pragma_table_info('$table') as ti"
		sqlite3 $dbfile "PRAGMA table_info('$table')" | awk -v t="$table" 'BEGIN { FS=OFS="|" } { $1=t; print $0 } '
		# Print index info
		#sqlite3 $dbfile "select '$table', ii.name, ii.\"unique\", ii.origin, ii.partial from pragma_index_list('$table') as ii"
		sqlite3 $dbfile "PRAGMA index_list('$table')" | awk -v t="$table" 'BEGIN { FS=OFS="|" } { $1=t; print $0 } '
		# Print triggers
		sqlite3 $dbfile "select '$table', type, rootpage, sql from sqlite_master where type='trigger' and tbl_name='$table'"
	done
}

if [[ -f $1 && -f $2 ]]; then
	diffopt="-y --expand-tabs --suppress-common-lines"
	normalize_schema $1 > cmpsql.s1
	normalize_schema $2 > cmpsql.s2
	if ! [[ -s cmpsql.s1 && -s cmpsql.s2 ]]; then
		echo "$(basename $0): ERROR: unable to read database table schema, cannot compare databases."
		exit 1
	fi
	difflst=$(diff $diffopt cmpsql.s1 cmpsql.s2)
	if [[ ${#difflst} -gt 0 ]]; then
		echo "WARNING: Found different schemas in $1 and $2"
		echo "Please investigate visually"
		echo "(Hint: this is the output of 'sqlite3 <dbfile> .schema')"
		echo -e "\n--- Schema for $1:"
		sqlite3 $1 '.schema' | grep -v 'TABLE sqlite_sequence'
		echo -e "\n--- Schema for $2:"
		sqlite3 $2 '.schema' | grep -v 'TABLE sqlite_sequence'
		echo
	else
		echo "Success: found identical schemas in $1 and $2"
	fi
else
	echo "$(basename $0): ERROR: could not find database files, cannot compare databases $1 and $2." ;
	exit 1;
fi
