#! /bin/sh

set -eu

if [ $# != 1 ]
then
	echo -e "usage:\nabyss-db-txt SQLite_repository"
	exit 1
fi

txt_filename=$1.txt
rm -f $txt_filename

tableArray=()
sqlite3 $1 "select name from sqlite_master where type='table' order by rootpage;" > temp
while read line
do
	tableArray+=(`echo ${line} | tr " " "\n"`)
done < temp
rm -f temp

if [ ${#tableArray[@]} -gt 0 ]
then
	for table in ${tableArray[@]}
	do
		echo -e "${table}\n" >> $txt_filename
		echo -e ".mode column\n.headers on\n.output ${table}\nselect * from ${table};\n.q" > $table
		sqlite3 $1 < $table
		cat $table >> $txt_filename
		echo -e "\n\n" >> $txt_filename
		rm -f $table
	done
	echo -e "Done! Check ${txt_filename} now."
	exit 0
fi
