#!/bin/sh
tmp1=tmp.1$$
tmp2=tmp.2$$
out=out
trap "rm -f $tmp1 $tmp2" 0 1 2 3 15
rm -f $tmp1 $tmp2 $out

loud=false
update_access_time=true
create_collections=true
create_collections_only=false
now=0
err=ok
while test $# -gt 0
do
	arg=$1
	case $arg in
	-uat)	update_access_time=true ;;
	+uat)	update_access_time=false ;;
	-cc)	create_collections=true ;;
	+cc)	create_collections=false ;;
	-cco)	create_collections_only=true ;;
	+cco)	create_collections_only=false ;;
	-v*)	loud=true ;;
	-help)	err=help ;;
	-now|-time)
		shift; if [ $# -eq 0 ]; then err="$arg syntax"; break; fi
		now=$1
		;;
	*)
		err="unknown arg $arg"
		break
		;;
	esac
	shift
	unset arg
done
if [ "$err" != "ok" ]; then
	if [ "$err" != "help" ]; then
		echo Error: $err 1>&2
	fi
	echo "Usage: `basename $0` [-v] [+uat] [-cc] [-cco] [-now time]" 1>&2
	echo "       where -now sets access times to specified value [default is current time]" 1>&2
	echo "             +uat disables update of access times" 1>&2
	echo "             +cc  disables creation of collections" 1>&2
	echo "             -cco creates collections only" 1>&2
	exit 1
fi
if [ $create_collections_only = true ]; then create_collections=true; fi

dbme ()
{
	coll=$1
	shift
	sqlite3 cc.db <<-EOF >$tmp2
	select p_uuid from "Entries" where p_type = "Collection" and p_titles_0_nominal = "$coll";
	EOF
	cid=`cat $tmp2`
	if [ -z "$cid" ]; then
		if [ $create_collections != true ]; then
			echo skip collection $coll without uuid
			continue
		fi
		cquote=`echo $coll | sed -e "s/'/''/g"`
		cstrip=`echo $coll | sed -e "s/['?!,\&;:\.]//g"`
		sqlite3 cc.db <<-EOF >$tmp2
		.load ./libfoo.so
		create temp table if not exists "tmp" ( p_uuid TEXT );
		delete from tmp;
		insert into tmp VALUES(uuidize(lower(hex(randomblob(16)))));
		INSERT INTO "Entries" VALUES((select p_uuid from tmp),'Collection',NULL,$now,NULL,0,'$cquote','$cstrip','$cquote','[{"direction":"LTR","collation":"$cstrip","pronunciation":"$cquote","display":"$cquote","language":"en-US"}]',1,NULL,'[]',0,'[]',0,'[]',0,NULL,NULL,NULL,NULL,NULL,1,1,NULL,0,0,NULL,'[]',0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'[{"ref":"titles"}]',NULL,NULL,NULL,NULL,NULL,NULL,0,2147483647,0,0);
		select p_uuid from tmp;
		EOF
		x=`wc -l $tmp2 | sed -e 's/^ * //' -e 's/ .*$//'`
		if [ "$x" != "1" ]; then
			exit 2
		fi
		if [ $x -ne 1 ]; then
			echo error creating uuid for collection $coll
			continue
		fi
		cid=`cat $tmp2`
	fi
	if [ $loud = true ]; then
		echo process collection $coll
	fi
	if [ $create_collections_only = true ]; then
		continue
	fi
	cat <<-EOF >>$out
	-- Collection: $coll
	DELETE FROM Collections WHERE i_collection_uuid = "$cid";
	EOF
	k=0
	members=
	for key in $*
	do
		: find books by key
		type=EBOK
		book=`echo $key | sed -e 's/^#//' -e 's/\^EBOK$//'`
		sqlite3 cc.db <<-EOF >$tmp2
		select p_uuid from "Entries" where p_type = "Entry:Item" and p_cdeKey = "$book" and p_cdeType = "$type" and p_location like "%/calibre/%";
		EOF
		bid=`cat $tmp2`
		if [ -z "$bid" ]; then
			type=PDOC
			book=`echo $key | sed -e 's/^#//' -e 's/\^PDOC$//'`
			sqlite3 cc.db <<-EOF >$tmp2
			select p_uuid from "Entries" where p_type = "Entry:Item" and p_cdeKey = "$book" and p_cdeType = "$type" and p_location like "%/calibre/%";
			EOF
			bid=`cat $tmp2`
		fi
		if [ -z "$bid" ]; then
			echo cannot find cdeKey $key from collection $coll
			continue
		fi
		: check that we only found one book with the key
		x=`wc -l $tmp2 | sed -e 's/^ * //' -e 's/ .*$//'`
		if [ "$x" != "1" ]; then
			exit 3
		fi
		if [ $x -ne 1 ]; then
			echo multiple books with cdeKey $book from collection $coll
			sqlite3 cc.db <<-EOF
			select p_titles_0_nominal,p_location from "Entries" where p_type = "Entry:Item" and p_cdeKey = "$book";
			EOF
			continue
		fi
		: find existing collection list for book
		sqlite3 cc.db <<-EOF >$tmp2
		select p_collectionCount,j_collections from "Entries" where p_uuid = "$bid";
		EOF
		c_numb=`cat $tmp2|sed -e 's/|.*$//'`
		c_list=`cat $tmp2|sed -e 's/.*|//' -e 's/]$//'`
		: add collection to book collection list
		if [ $c_numb -eq 0 ]; then
			c_list=$c_list\"$cid\"\]
		else
			c_list=$c_list,\"$cid\"\]
		fi
		c_numb=`expr $c_numb + 1`
		: update book collection list
		sqlite3 cc.db <<-EOF >$tmp2
		.load ./libfoo.so
		update "Entries" set p_collectionCount = $c_numb , j_collections = '$c_list' where p_uuid = "$bid";
		select p_titles_0_nominal from "Entries" where p_uuid = "$bid";
		EOF
		title=`cat $tmp2`
		if [ $loud = true ]; then
			echo "    $title"
		fi
		cat <<-EOF >>$out
		-- Entry: $title
		-- update "Entries" set p_collectionCount = $c_numb , j_collections = '$c_list' where p_uuid = "$bid";
		EOF
		: add title to collection
		k=`expr $k + 1`
		cat <<-EOF >>$out
		INSERT INTO "Collections" VALUES('$cid','$bid',$k,'$type','$book',1);
		EOF
		: add book to members
		if [ -z "$members" ]; then
			members=\"$bid\"
		else
			members=$members,\"$bid\"
		fi
	done
	cat <<-EOF >>$out
	-- Members of Collection: $coll
	update Entries set p_memberCount = $k , j_members = '[$members]' where p_uuid = "$cid";
	EOF
}

: keep mbak copies of the database
mbak=0
if [ $mbak -gt 0 ]; then
	rm -f cc.db.$mbak
	m=$mbak
	while [ $m -gt 1 ]
	do
		n=$m
		m=`expr $m - 1`
		if [ -f cc.db.$m ]; then
			mv -i cc.db.$m cc.db.$n
		fi
	done
	cp -p cc.db cc.db.1
fi

if [ $create_collections_only != true ]; then
	sqlite3 cc.db <<-EOF 1>$tmp2 2>$tmp1
	.load ./libfoo.so
	update "Entries" set p_collectionCount = 0 , j_collections = '[]' where p_type = "Entry:Item" and p_location like "%/calibre/%";
	create temp table if not exists "tmp" ( p_uuid TEXT );
	delete from tmp;
	insert into tmp VALUES(strftime('%s','now'));
	select p_uuid from tmp;
	EOF
	x=`wc -l $tmp1 | sed -e 's/^ * //' -e 's/ .*$//'`
	if [ "$x" != "0" ]; then
		cat $tmp1
		exit 1
	fi
	if [ "$now" = "0" ]; then
		now=`cat $tmp2`
	fi
fi

cat <<-EOF >$out
.load ./libfoo.so
BEGIN TRANSACTION;
EOF

cp collections.json $tmp2
echo "" >> $tmp2
sed -e '/^$/d' -e 's/^{//' -e 's/}$//' < $tmp2 > $tmp1

state=0
collection=
keys=
for line in `cat $tmp1`
do
	if [ $state -eq 0 ]; then
		if [ "$line" = '{"items":' ]; then
			state=1
			collection=`echo $collection | sed -e 's/^"//' -e 's/@[^@]*$//'`
			keys=
		elif [ -z "$collection" ]; then
			collection=$line
		else
			collection="$collection $line"
		fi
	elif [ $state -eq 1 ]; then
		if [ "$line" = '"lastAccess":' ]; then
			state=2
		else
			l=`echo $line | sed -e 's/[,"\[]//g' -e 's/]//g'`
			keys="$keys $l"
		fi
	elif [ $state -eq 2 ]; then
		dbme "$collection" $keys
		state=0
		collection=
	fi
done

if [ $update_access_time = true ]; then
	cat <<-EOF >>$out
	update "Entries" set p_lastAccess = $now;
	EOF
fi

cat <<-EOF >>$out
COMMIT;
.quit
EOF

if [ $create_collections_only != true ]; then
	sqlite3 cc.db < $out
fi

exit 0
