#!/bin/bash -e
# generate b.Tree with compile-time KEY=zodb.Oid, VALUE=int64, tuned kd and direct oidCmp calls

# Copyright (C) 2017  Nexedi SA and Contributors.
#                     Kirill Smelkov <kirr@nexedi.com>
#
# This program is free software: you can Use, Study, Modify and Redistribute
# it under the terms of the GNU General Public License version 3, or (at your
# option) any later version, as published by the Free Software Foundation.
#
# You can also Link and Combine this program with other software covered by
# the terms of any of the Free Software licenses or any of the Open Source
# Initiative approved licenses and Convey the resulting work. Corresponding
# source of such a combination shall include the source code for all other
# software used.
#
# This program is distributed WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING file for full licensing terms.
# See https://www.nexedi.com/licensing for rationale and options.

KEY=zodb.Oid
VALUE=int64

# adjust kd so that sizeof(d) ~= page
de=16	# KEY+VALUE
o=24	# d.c, d.n, d.p
kd=$(( (4096 - $o - $de) / (2 * $de) ))

# git_upstream_url <repo>   - show current branch upstream URL
git_upstream_url() {
	repo=$1
	head="`git -C $repo symbolic-ref --short HEAD`"             # current branch - e.g. "t"
	remote="`git -C $repo config --get branch.$head.remote`"    # upstream name, e.g. "kirr"
	url="`git -C $repo config --get remote.$remote.url`"        # upstream URL
	echo "$url"
}

b=github.com/cznic/b
Bdir=`go list -f '{{.Dir}}' $b`
Brev=`git -C $Bdir describe --always`
Bweb=`git_upstream_url $Bdir`
out=fsbtree.go

echo "// Code generated by gen-fsbtree from $b $Brev; DO NOT EDIT." >$out
echo "// (from patched version available at $Bweb)" >>$out
echo "//" >>$out
echo "// KEY=$KEY  VALUE=$VALUE" >>$out
echo "// ---- 8< ----" >>$out
echo >>$out
make -s -C $Bdir generic |sed	\
	-e '/package b/a \\nimport "lab.nexedi.com/kirr/neo/go/zodb"'	\
	-e 's/package b/package fsb/g'	\
	-e "s/KEY/$KEY/g"	\
	-e "s/VALUE/$VALUE/g"	\
 \
	-e "s/^\(\\s*kd = \).*\$/\\1$kd/g"	\
 \
	-e '/cmp *Cmp$/d'	\
	-e 's/t\.cmp(/oidCmp(/g'	\
	-e 's/func TreeNew(cmp Cmp)/func TreeNew()/g'	\
	-e 's/btTPool.get(cmp)/btTPool.get()/g'	\
	-e 's/func (p \*btTpool) get(cmp Cmp)/func (p *btTpool) get()/g'	\
	-e '/x\.cmp = cmp$/d'	\
	>>$out

# also extract dump() routine
out=fsbtree_util.go
echo "// Code generated by gen-fsbtree from $b $Brev; DO NOT EDIT." >$out
echo "// (from patched version available at $Bweb)" >>$out
echo "//" >>$out
echo "// ---- 8< ----" >>$out
echo >>$out
cat >>$out <<EOF
package fsb
import (
	"bytes"
	"github.com/cznic/strutil"	// XXX better to not depend on it
)
EOF
echo >>$out
sed -n	\
	-e '/^func isNil(/,/^}/p'	\
	-e '/^func.* dump()/,/^}/ {
		s/dump()/Dump()/g
		s/v\.k != nil/v.k != 0/g
		s/v\.v != nil/v.v != 0/g
		p
	}'	\
 \
	$Bdir/all_test.go	\
	>>$out
