#
#	common lib among Kirara1 and Kirara2
#
# cp -x klib ../kirara1
# cp -x klib ../kirara2

fn usage {
u1=''
u2=''
if(test -e eventlog){
	u1='[-L] '
	u2=$nl'  -L	# update using event log'
}
echo 'usage: mkdb [-b] [-r [$dir ... ]] [-u $dir ...] '$u1'[-C]
select one of options below:
  -b	# build from scratch
  -r	# update the dirs and the subdirs using $target
  -r $dir ...	# update the dirs and the subdirs
  -u $dir ...	# update the dirs (only the dirs)'$u2'
  -C	# check database
under "-r" or "-u" mkdb recontructs indexes assuming existing
indexes are not broken.
NB: except fossil, both "-r" and "-u" options may miss update
due to mtime bug of directories.'
exit usage
}

fn laptime {
	t1=() {
	t1=`{date -n}
	echo $1 `{echo -n $t1 $2 - p | dc}
	}
}

fn join {
	# usage: join $c arg ...
	c=() r=() {
	c=$1
	shift
	r=$1
	shift
	for(a in $*)
		r=$r$c$a
	echo -n $r
	}
}

fn ge_to_re {
	# glob expression to regular expression
	# we don't support "\" escape of ge
	# supported symbols of ge: "?", "*", "[", "]", "[~"
	# "|", "(" and ")" works as extended glob expression
	# we assume following special symbols of re is not in ge
	# "\", "$", "^"
	ifs=() {echo $1 | sed 's/\./\\./g; s/\?/./g; s/\*/.*/g; s/\[~/[^/g'}
}

fn fsize {
	size=() {
	size=`{ls -l $1}
	echo $size(6)
	}
}

fn chkargs {
	# usage: chkargs $arg ...
	for(d in $*){
		if(~ $d */){
			echo '# remove last / in' $d >[1=2]
			exit usage
		}
	}
}

fn chkqtp1 {
	# usage: chkqtp1 qtp
	sort -t $tab +0 $1 > _chkqtp1_sort
	uniqx -dF $tab -k 0 _chkqtp1_sort | awk '{print $1}' > _chkqtp1_q	# print duplicated qid
	ffm -f1 -F $tab _chkqtp1_q _chkqtp1_sort
}

fn chkqtp3 {
	# usage: chkqtp qtp
	sort -t $tab +2 $1 > _chkqtp3_sort
	uniqx -dF $tab -k 2	_chkqtp3_sort | awk '{print $3}' > _chkqtp3_p # print duplicated path
	ffm -f3 -F $tab _chkqtp3_p _chkqtp3_sort
}

fn fixqtp1 {
	# usage: fixqtp1 qtp
	sort -t $tab $1 | uniqx -rF $tab -k 0
}

fn fixqtp3 {
	# usage: fixqtp3 qtp
 	# sort name and then time
	# if time is same, the result may be wrong.
	# then next later step will fix the result.
	sort -t $tab +2 +1 -2 $1 | uniqx -rF $tab -k 2
}


fn mkqp {
	# usage: mkqp $qtp > $qp
	# usage: | mkqp > $qp
	awk -F $tab '{print $1 "\t" $3}' $*
}

fn mkq {
	# usage: mkq $qtp > $q
	# usage: | mkq > $q
	awk -F $tab '{print $1}' $*
}

fn subtree1 {
	# usage: subtree1 $re_file $qff
	# first subtree from $qff using $re_file
	# consider the case that $re_file contains
	#	/usr/arisawa/doc/libc/TLS/
	# and the second field of $qf contains:
	#	/usr/arisawa/doc/libc/etc...
	#	/usr/arisawa/doc/libc/TLS/
	#	/usr/arisawa/doc/libc/TLS/foo/bar
	#	/usr/arisawa/doc/libc/TLS/baz
	# we wanto only the dir entry of /usr/arisawa/doc/libc/TLS
	#	/usr/arisawa/doc/libc/TLS/
	#	/usr/arisawa/doc/libc/TLS/foo/
	#	/usr/arisawa/doc/libc/TLS/baz

	ffm -mKf3 -F $tab $1 $2 |\
	awk '{
	s1=substr($3,$4+1)
	if(length(s1)){ # submatch
		m=match(s1,"[^/]*/.+")
		if(!m)
			print $1 "\t" $2 "\t" $3
	}
	else
		print $1 "\t" $2 "\t" $3
	}' | sort -ut $tab +2 +1
	# NB: prevent duplication
}

fn subtree {
	# usage: subtree $re_file $qf
	# extract subtree from $qf using $re_file

	ffm -mf2 -F $tab $1 $2 |\
	awk '{print $0}' | sort -ut $tab +1 +0
	# NB: prevent duplication
}

fn mkqdic_old {
	# usage: mkqdic [-u] [-b] $qf ... | sort -u > main
	# the output is lines of $word $tab $qid
	# why we need dictionary?
	# because to speed up retrieval from large text file
	# there are so many meta characters in rc.
	# ;$^{}[] etc
	# the safest way is enclose whole string by "'"
	opt=-b
	if(~ $1 -*){
		opt=$1
		shift
	}
	# Kirara-2.2 does not require qid
	awk -F $tab -v 'opt='$opt '
	function quote(s){ gsub("''","''''", s); return "''" s "''" }
	{ print "mkkind '$opt' " quote($2)}' $* > _rc
	. ./_rc
}


fn mkqdic {
	# usage: mkqdic [-u] [-b] $f ... | sort -u > main
	# $f is a file
	# Kirara-2.2 does not require qid
	# the output is lines of $word $tab $qid
	# why we need dictionary?
	# because to speed up retrieval from large text file
	# there are so many meta characters in rc.
	# ;$^{}[] etc
	# the safest way is enclose whole string by "'"
	opt=-b
	if(~ $1 -*){
		opt=$1
		shift
	}
	awk -F $tab -v 'opt='$opt '
	function quote(s){ gsub("''","''''", s); return "''" s "''" }
	{ print "mkkind '$opt' " quote($1)}' $* > _rc
	. ./_rc
}


fn rmqdir {
	# usage: rmqdir $q
	# $q is a file
	# or $qf, $qtf, $qd, $qtd are OK instead of $q
	if(test -s $q)
		9xa -f $q rm -rf 
}

fn mergedb {
	# usage: mergedb _qtp_update _qtp_rename _q_remove
	# where _qtp_update and _qtp_rename is new onw
	# output: main mtoc qtp qp
	# where p denote path
	# p -> d for Kirara1
	# p -> f for Kirara2
	#
	#	excute (fix qtp and qp)
	#	input: qtp qp _qtp_rm _qtp_up
	#
	qtp_update=() qtp_rename=() q_remove=() qtp=() qp=() {
	qtp_update=$1 # update+create
	qtp_rename=$2 # produced by rename
	q_remove=$3   # gone

	qtp=`{echo qt[df]}
	qp=`{echo q[df]}

	mkq $qtp_update $qtp_rename $q_remove > _q_x
	ffm -vf1 -F $tab _q_x $qtp > _qtp
	cat $qtp_update $qtp_rename >> _qtp	# not sorted
	mkqp _qtp > _qp	# not sorted

	#
	#	excute
	#

	rmqdir $q_remove

	> _rb_m
	> _q_m
	### NB: due to mtime bug of cwfs,  we also need to update $qtp_rename
	#if(test -s $qtp_update){
	#	mkqp $qtp_update > _qp_update
	#	mkqdic -u _qp_update | sort -u >> _rb_m
	#	mkq _qp_update >> _q_m
	#}
	cat $qtp_update $qtp_rename > _qtp_uprn
	if(test -s _qtp_uprn){
		mkqp _qtp_uprn > _qp_uprn
		awk -F $tab '{print $2}' _qp_uprn > _p_uprn
		mkqdic -u _p_uprn | sort -u >> _rb_m
		mkq _qp_uprn >> _q_m
	}


	laptime mkqdic $t0

	if(! test -s $q_remove && ! test -s _rb_m && ! test -s _q_m){
		mv _qtp $qtp
		mv _qp $qp
		laptime done $t0
		exit
	}

	#awk -F $tab '{print $2}' _rb_m >> _q_m
	cat $q_remove >> _q_m
	ffm -vf2 -F $tab _q_m main | merge _rb_m > _main	# sorted

	laptime merge $t0

	# in case of old way (Kirara ver.1)
	# double times faster than using mkdict
	mktoc _main > _mtoc
	mv _mtoc mtoc
	mv _main main

	# for the temporally we keep old data for debugging
	mv $qtp $qtp.old	#DBG
	mv $qp $qp.old		#DBG

	mv _qtp $qtp
	mv _qp $qp

	# NB: making compressed data takes much time
	# and meaningless if we left uncompressed data.
	# so I stopped to use mkdict, instead took a Kirara ver.1 way.
	# I take updating speed rather than disk space
	#mkmind _main
	#mv _main main
	#mv indx:_main indx:main
	#mv dict:_main dict:main
	#mv list:_main list:main
	}
}

fn rdeventlog {
	# usage: rdeventlog
	# the output is a list of dirs that we must try to updata
	# some of these dirs might not exist (already gone)
	if(~ $#eventlog 0){
		echo 'no event log' >[1=2]
		exit 'no event log'
	}

	# analysis of event log
	# the example
	# maia	Jun	14	16:50:39	wopen:	/usr/arisawa/netlib/kirara/CHANGES
	# maia	Jun	14	16:50:39	mtime:	/usr/arisawa/netlib/kirara/CHANGES
	# 
	# $eventlog is "%q" string. (rc style quoted string)
	# we need to convert the string to tab separated one

	# we need to remove irrelevant directories from log 
	# and directories in $exclude should also be eliminated.
	# and then extract logs from last update

	ifs=() s=`{join /$nl $target} echo $s/ > _target

	m=`{mtime $eventlog} {t0=$m(1)} # on /sys/log
	m=`{mtime eventlog} {t1=$m(1)}	# on $kirara?/*db
	ifs="T+"$nl m=`{date -t $t0 | sed 's/-/\//g'} {lt=($m(1) $m(2))}
	ifs="T+"$nl m=`{date -t $t1 | sed 's/-/\//g'} {kt=($m(1) $m(2))}

	# lt: mtime of $eventlog
	# kt: mtime of eventlog
	# these format is such as: (2014/04/01 23:59:56)
	#echo '#lt' $lt >[1=2]	#DBG
	#echo '#kt' $kt >[1=2]	#DBG
	#echo '#eventlog' $eventlog >[1=2]	#DBG
	#cat _target >[1=2]	#DBG

	unq $eventlog | sed 's:'$tab'\./:'$tab'/usr/:g' |\
		ffm -mf6 -F $tab _target |\
		awk -v 'lt='$"lt -v 'kt='$"kt '
		BEGIN{ mon["Jan"]=1; mon["Feb"]=2; mon["Mar"]=3; mon["Apr"]=4;
		  mon["May"]=5; mon["Jun"]=6; mon["Jul"]=7; mon["Aug"]=8;
		  mon["Sep"]=9; mon["Oct"]=10; mon["Nov"]=11; mon["Dec"]=12;
		  m=index(lt,"/"); y0=substr(lt,1,m-1); t0=substr(lt,m+1)
		}
		function fix(t) {
		  if(t > lt)
		    return sprintf("%02d",y0-1) "/" t
		  else
		    return y0 "/" t
		}
		{
		  t=sprintf("%02d/%02d %s\n", mon[$2], $3, $4)
		  t=fix(t)
		  if(t > kt) print $0
		}' > _eventlog
		#cat _eventlog >[1=2]	#DBG

	#
	# we discard details and extract relevant dirs.
	# events from eventlog are:
	# 	create	path
	# 	wopen	path
	# 	remove	path
	# 	mtime	path
	# 	wstat	path
	# 	rename	path newname
	# paths with tailing "/" are directory


	awk -F $tab '
	function dir(f){
		# extract hosted directory
		# ./arisawa/foo/bar -> ./arisawa/foo/
		# ./arisawa/foo/bar/ -> ./arisawa/foo/bar/
		n=match(f,".+/")	# longest match
		if(n)
			return substr(f,RSTART,RLENGTH)
		return f
	}
	function dir1(f){
		# extract hosted directory
		# ./arisawa/foo/bar -> ./arisawa/foo/
		# ./arisawa/foo/bar/ -> ./arisawa/foo/
		if(match(f,"/$"))
			f = substr(f,1,length(f)-1)
		n=match(f,".+/")	# longest match
		if(n)
			return substr(f,RSTART,RLENGTH)
		return f
	}
	$5 ~ /rename/ {
		#   rename: ./arisawa/src/foo/ bar		# directory renaming
		#   rename: ./arisawa/src/foo bar		# file renaming
		# those output should be:
		#	./arisawa/src/
		# and also if foo is directory:
		#	./arisawa/src/foo/
		#	./arisawa/src/bar/
		d=dir1($6)		# d is /usr/arisawa/src/
		if(match($6,"/$")){
			for(k in kdb){
				len = length($6)
				if(substr(k,1,len) == $6){
					t = d $7 "/" substr(k,len+1)
					delete kdb[k]
					kdb[t] = 1
					#print "# del:" k
					#print "# rep:" t
				}
			}
			kdb[d $7 "/"] = 1
		}
		kdb[d] = 1
		next
	}
	$5 ~ /remove/ {
		#   remove: ./arisawa/src/foo/		# directory removal
		#   remove: ./arisawa/src/foo		# file removal
		d = dir1($6)	# output must be existing dir, so dir1($6)
		if(match($6,"/$"))
			delete kdb[$6]
		kdb[d] = 1
		next			
	}
	$6 ~ /\/$/ {			# something happend to the dir 
		kdb[$6] = 1
		kdb[dir1($6)] = 1
		next
	}
	{
		d = dir($6)
		kdb[d] = 1		# something happend to the file
	}
	END{
		for(k in kdb){
			print k
		}
	}' _eventlog | sort -u | sed 's!/$!!g' >_elog
	# format of _elog
	# /usr/arisawa/src/Kirara/dbtest
	# /usr/arisawa/src/UNQ
	# /usr/arisawa/src/unq

	grep -v $exclude _elog

	# $exclude must be here
	# we must be careful not to remove events such as
	# 	remove: /foo/bar/baz1.8
	# 	remove: /foo/bar/baz2.8
	# 	remove: /foo/bar/..
	# otherwise, the change of time stump of bar may be hidden.
	# (if baz.c is in bar, then the line is left and change of bar is detected.)


	# the output is a list of dirs that may be:
	# removed
	# created
	# updated

	exit ''		# we need this one for normal exit
}

fn updlog {
	elog=$eventlog klog=() m=() t0=() t1=() kt=() lt=() {

	if(! ~ $#kirara1 0)
		klog=`{ls $kirara1/usr*db/eventlog}
	if(! ~ $#kirara2 0)
		klog=($klog `{ls $kirara2/usr*db/eventlog})

	if(~ $#klog 0)
		exit

	m=`{mtime $elog} {t0=$m(1)}
	
	# get the oldest(smallest mtime) update
	t1=$t0
	for(f in $klog){
		m=`{mtime $f} {t=$m(1)}
		if(test $t -lt $t1) t1=$t
	}
	ifs="T+"$nl m=`{date -t $t1 | sed 's/-/\//g'} {kt=($m(1) $m(2))}
	ifs="T+"$nl m=`{date -t $t0 | sed 's/-/\//g'} {lt=($m(1) $m(2))}
	# lt: mtime of $eventlog
	# kt: smallest mtime of $klog
	# these format is such as: (2014/04/01 23:59:56)
	
	awk -v 'lt='$"lt -v 'kt='$"kt '
	BEGIN{ mon["Jan"]=1; mon["Feb"]=2; mon["Mar"]=3; mon["Apr"]=4;
	  mon["May"]=5; mon["Jun"]=6; mon["Jul"]=7; mon["Aug"]=8;
	  mon["Sep"]=9; mon["Oct"]=10; mon["Nov"]=11; mon["Dec"]=12;
	  m=index(lt,"/"); y0=substr(lt,1,m-1); t0=substr(lt,m+1)
	}
	function fix(t) {
	  if(t > lt)
	    return sprintf("%02d",y0-1) "/" t
	  else
	    return y0 "/" t
	}
	{
	  t=sprintf("%02d/%02d %s\n", mon[$2], $3, $4)
	  t=fix(t)
	  if(t > kt) print $0
	}' $elog > _updlog_t

	chmod -a $elog && cat _updlog_t > $elog && chmod +a $elog
	#rm _updlog_t
	}
}
