#!/bin/rc
# cp -x mkdb ../sysdb
# cp -x mkdb ../usrdb
# cp -x mkdb ../usr1db
# cp -x mkdb ../usr2db

rfork e

. db.conf

sp=' '
tab='	'
nl='
'	# new line

ifs0=$sp$tab$nl
ifs=$ifs0

fn mkqtf {
	# usage: mkqtf [-r] $target ... > $qtf
	# -r	# recursive
	# some of binary files are eliminated here
	# now, we don't need sort, because we use ffm
	# NB: du does not sort, so also mkqtf
	# NB: the output may be duplicated. for example,
	#	mkqtf /foo/src /foo/src/lua
	# such case may happen only in log update
	# so you may need:
	#	mkqtf $target | sort -u +t2
	#
	#echo '# mkqtf:' $* >[1=2] 
	opt=(){
	if(~ $1 -r){
		opt=-r
		shift
	}
	if(~ $#* 0){
		echo 'no argus in mkqtf' >[1=2]
		exit error
	}
	if(~ $opt -r){
		if(~ $#exclude 0){
			{lr -lqnQD0 $*; du -f $* |unq| awk -F $tab '{print $2}' | 9xa lr -lqQnD1} |\
			awk -F $tab '
			$4 ~ /^d/ {print $1 "\t" $8 "\t" $9 "/"; next}
			$7 !~ /^0$/ {print $1 "\t" $8 "\t" $9}'
		}
		if not{
			{lr -lqnQD0 $*; du -f $* |unq| awk -F $tab '{print $2 "/"}' | fgrep -v $exclude |\
			9xa lr -lqQnD1} |\
			awk -F $tab '
			$4 ~ /^d/ {print $1 "\t" $8 "\t" $9 "/"; next}
			$7 !~ /^0$/ {print $1 "\t" $8 "\t" $9}
			' | fgrep -vf3 -F $tab $exclude
		}
	}
	if not { # log update
		if(~ $#exclude 0){
			lr -lqQnd1 $* |\
			awk -F $tab '
			$4 ~ /^d/ {print $1 "\t" $8 "\t" $9 "/"; next}
			$7 !~ /^0$/ {print $1 "\t" $8 "\t" $9}
			'
		}
		if not {
			lr -lqQnd1 $* |\
			awk -F $tab '
			$4 ~ /^d/ {print $1 "\t" $8 "\t" $9 "/"; next}
			$7 !~ /^0$/ {print $1 "\t" $8 "\t" $9}' |\
			fgrep -vf3 -F $tab $exclude
		}
	}
	}
}

fn stat {
	# usage: stat $target
	# get total size of indexed text
	if(! ~ $#exclude 0){
		# submatch
		du $* |unq| awk -F $tab '{print $2 "/"}' | fgrep -v $exclude | 9xa lr -lqQnD 1 |\
		awk -F $tab '
		$4 ~ /^d/ {next}
		$7 !~ /^0$/ {print $1 "\t" $7 "\t" $8 "\t" $9}
		' | grep -v $exclude > _stat_qstf
	}
	if not{
		du $* |unq| awk -F $tab '{print $2}' | 9xa lr -lqQnD 1 |\
		awk -F $tab '
		$4 ~ /^d/ {next}
		$7 !~ /^0$/ {print $1 "\t" $7 "\t" $8 "\t" $9}
		' > _stat_qstf
	}
	echo '# wc _stat_qstf'
	wc _stat_qstf
	awk -F $tab '{print $2}' main |sort -u > _stat_q_main
	echo '# wc _stat_q_main'
	wc _stat_q_main
	ffm -f1 -F $tab _stat_q_main _stat_qstf > _stat_qstf_text
	echo '# total size of text files'
	awk -F $tab '{sum += $2}END{print sum}' _stat_qstf_text

	awk -F $tab 'BEGIN{zero=0;tiny=0;small=0;medium=0;larg=0;}
	{
	  if($2 == 0){zero++; next;}
	  if($2 < 100000) {tiny++; next;}
	  if($2 < 1000000) {small++; next;}
	  if($2 < 10000000) {medium++; next}
	  large++;
	}
	END{print zero, tiny, small, medium, large}' _stat_qstf_text
}

fn build {
	# build from scratch
	# usage: build
	echo $target #DBG

	if(test -e find){
		echo 'found old data. removing find' >[1=2]
		rm -rf find
	}

	if(test -e qdir)
		rm -rf qdir
	mkdir qdir

#	laptime rmdir $t0

	mkqtf -r $target > qtf
	laptime mkqtf $t0
	mkqp qtf > qf	# qf is used in kfind2
	laptime mkqf $t0

	awk -F $tab '{print $2}' qf > _f
	mkqdic -b _f > _m
	sort -u _m > main
	rm _m
	laptime mkqdic $t0

	mktoc main > mtoc
	# look the comment in update for not using mkmind (mkdict)
	# mkmind main
	laptime done $t0
}

fn update {
	# usage: update [-r|-u] $target
	# the target of update is existing dirs
	# non-existent is simply discarded
	# update assumes qf,qtf, and main are not broken

	opt=()
	while(~ $1 -*){
		opt=$1
		shift
	}

	if(~ $#opt 0){
		echo 'need -r or -u option' >[1=2]
		exit usage
	}
	if(! ~ $opt -r -u){
		echo 'invalid option' >[1=2]
		exit usage
	}
	if(~ $#* 0){
		echo 'no update' >[1=2]
		exit no_update
	}

	#echo $* >[1=2]	 #DBG
	ifs=() t=`{join /$nl $*} echo $t/ | ffm -mf1 -F $tab _target > _args
	args=`{sed 's:\/$::g' _args}
	echo $args >[1=2]	#DBG
#exit DBG
	# for the temporally, we check qtf and fix it
	# check qtf
	fixqtp1 qtf > _t
	size0=`{fsize qtf}
	size1=`{fsize _t}
	if(test $size0 -ne $size1){
		echo 'dup qid. fixing'
		mv _t qtf
		mkqd qtf > qf
	}

	# the args for mkqtf must be existing dirs
	# now output of rdeventlog is only existing dirs

	for(f in $*){
		if(! test -d $f){
			echo $f 'non-exitent or not a dir'
			exit usage
		}
	}

	
	if(~ $opt -r){
		mkqtf -r $args > _qtf1	# _qtf1 is a portion of the system
		ffm -mf3 -F $tab _args qtf | ffm -vf3 -F $tab _args > _qtf0
	}
	if not {
		# this is the most difficult part in mkdb
		# update assumes qf,qtf, and main are not broken
		
		# you might wonder why qtf include dirs.
		# the dirs is required to handle direcory renaming.
		# if qtf doen't include dir info, it is impossible to detect renaming.
				
		# consider a case that $home/foo/bar/ is renamed to $home/foo/baz/
		# more complicated case:
		# consider $home/foo/bar/huga. huga is removed and then foo is renamed to hoge
		# how to relect the change to qtf and qf?
		
		# $args is a list of dirs that happend something
		# the output of mkqtf may be duplicated
		mkqtf $args | sort -ut $tab +2 > _qtf1+
		mkqp _qtf1+ > _qf1+
		# _qtf1+ include so many dirs.
		# we want to have the counter parts: _qtf0+
		#echo $args >[1=2]	#DBG
		#cat _qtf1 >[1=2]	#DBG

		mkq _qf1+ > _q1+
		ffm -f1 -F $tab _q1+ qf | sort -ut $tab +1 > _qf0+	# partial contents
		# _qf0+ is the counter part of _qf1+
		# NB: removed contents are not in _qf0+
		# we can know only create, update and rename comparing _qf0+ and _qf1+

		# assuming that removed names are not one of $target
		# the those names can be found as the following process:
		# (1) discard common parts
		ffm -f1 -F '' _qf0+ _qf1+ > _qf+_co		# common parts
		ffm -vf1 -F '' _qf+_co _qf0+ > _qf0r	# the rest (rename)
		ffm -vf1 -F '' _qf+_co _qf1+ > _qf1r	# the rest (rename)
		mkq _qf0r > _q0r
		mkq _qf1r > _q1r
		ffm -f1 -F $tab _q0r _q1r > _q_co
		ffm -f1 -F $tab _q_co _qf0r | sort > _qf0r_co
		ffm -f1 -F $tab _q_co _qf1r | sort > _qf1r_co
		/bin/join -t $tab _qf0r_co _qf1r_co |\
			awk -F $tab '{print $2 "\t" $3}' > _tr_map
		#cat _tr_map >[1=2]	#DBG
		awk -F $tab '{print $2 "\t" $1}' _tr_map > _tr_map_rev	# reverse map
		#cat _tr_map_rev >[1=2]	#DBG
		if(test -s _tr_map_rev)
			eKR_trans -F $tab _tr_map_rev _args > _args0
		if not
			cat _args > _args0
		subtree1 _args0 qtf > _qtf0+	# counter part of _qtf1+
		# discard common lines
		ffm -f1 -F '' _qtf0+ _qtf1+ > _qtf+_co
		# ffm -vf1 -F '' _qtf+_co _qtf0+ > _qtf0	#BUG
		# ffm -vf1 -F '' _qtf+_co _qtf1+ > _qtf1	#BUG
		# don't stop here!
		# _qtf0 and _qtf1 must cover all relevant names.

		ffm -vf1 -F '' _qtf+_co _qtf0+ > _qtf0+r
		ffm -vf1 -F '' _qtf+_co _qtf1+ > _qtf1+r
		# from _qtf0+r and _qtf1+r, we can detect removed qid
		mkq _qtf0+r > _q0+r
		mkq _qtf1+r > _q1+r
		#ffm -vf1 -F $tab _q1+r _q0+r > _q0_rm	# removed

		awk -F $tab '{print $3}' _qtf0+r > _f0+r
		awk -F $tab '{print $3}' _qtf1+r > _f1+r

		ffm -mf3 -F $tab _f0+r qtf | sort +2 > _qtf0
		if(test -s _tr_map)
			eKR_trans -F $tab _tr_map _qtf0 > _qtf1
		if not
			cat _qtf0 > _qtf1

		# we must remove some names in _f1+r_tr from _qtf1
		if(test -s _tr_map)
			eKR_trans -F $tab _tr_map _f0+r > _f1+r_tr
		if not
			cat _f0+r > _f1+r_tr
		ffm -vf1 -F $tab _f1+r _f1+r_tr > _f1+r_rm	# removed dir
		ffm -vmf3 -F $tab _f1+r_rm _qtf1 > _t
		mv _t _qtf1

		# time field in _qtf1 is old one. we must fix
		cat _qtf1 _qtf1+r | sort +2 +1 | uniqx -rfF $tab -k 2 > _t
		mv _t _qtf1
		# we restrict to:
		ffm -mf3 -F $tab _f1+r _qtf1 > _t
		mv _t _qtf1
	}
#exit DBG
	# input: _qtf0  _qtf1
	# fields in _qtf0 and _qtf1 are tab separated.
	# therefore the next two are exact line match.
	ffm -vf1 -F '' _qtf1 _qtf0 > _qtf_gone	# that are only qtf
	ffm -vf1 -F '' _qtf0 _qtf1 > _qtf_new	# that are only current fs
	awk -F $tab '{print $1 "\t" $3}' _qtf_gone > _qf_gone
	awk -F $tab '{print $1 "\t" $3}' _qtf_new  > _qf_new
	ffm -f1 -F '' _qf_gone _qf_new > _qf_comm	# that's updated
	ffm -vf1 -F '' _qf_gone _qf_new > _qf_crrn	# that's created or renamed(to)
	ffm -vf1 -F '' _qf_new _qf_gone > _qf_rmrn	# that's removed or renamed(from)

	mkq _qf_comm > _q_up
	mkq _qf_crrn > _q_crrn
	mkq _qf_rmrn > _q_rmrn

	ffm -f1 -F '' _q_crrn _q_rmrn > _q_rn	# rename
	ffm -vf1 -F '' _q_rn _q_rmrn > _q_rm	# remove
	ffm -vf1 -F '' _q_rn _q_crrn > _q_cr	# create

	cat _q_up _q_cr > _q_crup
	ffm -f1 -F $tab _q_crup  _qtf_new | ffm -mf3 -F $tab _target > _qtf_update

	> _qtf_rename
	if(test -s _q_rn){
		# for renaming
		ffm -f1 -F $tab _q_rn  _qtf_new | sort -t $tab > _qtf_rename1	# new
		ffm -f1 -F $tab _q_rn  _qtf_gone | sort -t $tab > _qtf_rename0	# old
		cat _qtf_rename1 > _qtf_rename
	}

	laptime ready $t0
#exit DBG
	# finally:
	mergedb _qtf_update _qtf_rename _q_rm
	# usage: mergedb _qtp_update _qtp_rename _q_remove
	# where _qtp_update and _qtp_rename is new one

	laptime done $t0
}

fn delete {
	# usage: delete $dir
	# delete $dir and the subtree from database
	# delete assumes qf,qtf, and main are not broken
	if(~ $#* 0)
		usage
	ifs=() t=`{join /$nl $*} echo $t/ > _rm_args

	# if $* is (foo bar), then _rm_args is
	# foo/
	# bar/

	ffm -mf3 -F $tab _rm_args qtf > _rm_qtf_rm
	awk -F $tab '$3 !~ /\/$/ {print $1}' _rm_qtf_rm > _rm_q

	if(! test -s _rm_q)
		exit

	ffm -vmf3 -F $tab _rm_args qtf > _rm_qtf_rest
	mkqp _rm_qtf_rest > _qf

	ffm -vmf2 -F $tab _rm_q main > _main
	mktoc _main > _mtoc

	#echo debug: not deleted
	#exit

	# real actions are here
	rmqdir _rm_q
	mv _mtoc mtoc
	mv _main main
	mv qtf qtf.old
	mv _rm_qtf_rest qtf
	mv qf qf.old
	mv _qf qf

	#mkmind main
}

fn chkdupf {
	# usage: chkdupf $qtf
	sort -t $tab +2 $1 > _chkdupf_f
	awk -F $tab '{if($3 <= prev) { print "# duplicated\n" prev "\n" $3; exit "duplicated"};
	prev=$3
	}' _chkdupf_f
}

fn chksort {
	# usage: chksort main
	awk '{if($0 "" <= prev "") { print prev "\n" $0; exit "not sorted"};
	prev=$0
	}' $1
}

fn chkdb {
	# usage: chkdb

	echo '# checking duplicated qid in qtf'
	chkqtp1 qtf > _ch_qtf_dup_q
	if(test -s _ch_qtf_dup_q){
		cat _ch_qtf_dup_q
		echo -n 'fix? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y){
			fixqtp1 qtf > _t
			mv _t qtf
		}
	}

	echo '# checking duplicated path in qtf'
	chkqtp3 qtf > _ch_qtf_dup_path
	if(test -s _ch_qtf_dup_path){
		cat _ch_qtf_dup_path
		echo -n 'fix? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y){
			# 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.
			fixqtp3 qtf > _t
			mv _t qtf
		}
	}

	echo '# checking consistency of qtf to real world'
	mkqtf -r $target > _ch_qtf1		# real world
	ffm -vF '' _ch_qtf1 qtf > _ch_qtf00
	ffm -vF '' qtf _ch_qtf1 > _ch_qtf11

	# we don't mind time stamp of dirs, so ...
	# extract files
	grep '[^/]$' _ch_qtf00 > _ch_qtf00_file
	grep '[^/]$' _ch_qtf11 > _ch_qtf11_file

	if(test -s _ch_qtf00 || test -s _ch_qtf11){
		echo '# you need not mind time field of directory'
		# look comment in rdeventlog in klib
		if(test -s _ch_qtf00){
			echo '# files that are in qtf but not in real world'
			cat _ch_qtf00
		}
		if(test -s _ch_qtf11){
			echo '# files that are in real world but not in qtf'
			cat _ch_qtf11
		}
		echo -n 'fix? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y){
			mv _ch_qtf1 qtf
			mkqp qtf > qf
		}
	}

	laptime check_qtf $t0

	echo '# cheking qdir/*'
	ls -p qdir > _ch_q1
	mkq qf > _ch_q0
	ffm -v -F $tab -f1 _ch_q0 _ch_q1 > _ch_q11
	ffm -v -F $tab -f1 _ch_q1 _ch_q0 > _ch_q00
	if(test -s _ch_q11){
		echo '# qid that are in qdir but not in qf'
		ffm -f1 -F $tab _ch_q11 qf > _ch_q11_qf
		if(test -s _ch_q11_qf){
			cat _ch_q11_qf
			echo -n 'remove redundant qdir? (Y/n)'
			a=`{read}
			if(~ $#a 0 || ~ $a Y y)
				rmqdir _ch_q11
		}
	}

	# we need not mind _ch_q00

	laptime check_qdir $t0

	#
	# index check
	#

	echo '# checking qid in main if they are in qf'
	ffm -vf2 -F $tab _ch_q0 main > _ch_q_main
	if(test -s _ch_q_main){
		echo '# qids that are in main but not in qf'
		echo '# only 10 lines are shown below:'
		sed 10q _ch_q_main
		echo -n 'remove redundant qid in main and remake mtoc? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y){
			awk -F $tab '{print $1}' qf > _ch_q
			ffm -f2 -F $tab _ch_q main > _ch_m
			mv _ch_m main
			mktoc main > mtoc
		}
	}

	# NB: the routine below is not applicable to old Kirara2
	# because mkqdic of old Kiarar2 requires qid
	echo '# checking qid in main if some qids are lost or not'
	awk -F $tab '{print $2}' main > _ch_q_main
	ffm -vf1 -F $tab _ch_q_main qf | grep -v '/$' | awk -F $tab '{print $2}' |\
	grep -v '\/$|'$exclude |\
	9xa extwords -il $wordlen |\
	awk '
		/:$/{ prev = $0; next }
			{  if(prev && $0 != prev){
					# the prev is such as "/foo/bar:". we would like to have "/foo/bat"
					print substr(prev,0,length(prev) -1);
					prev = 0;
				}
			}
		' | sort -u > _ch_main_lost
	# example in _ch_d_main_lost
	# /usr/arisawa/bin/rc/photo/mkf
	# /usr/arisawa/bin/rc/photo/mki
	# they are files
	if(test -s _ch_main_lost){
		sed 10q _ch_main_lost
		echo -n 'fix main and remake mtoc? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y){
			mkqdic _ch_main_lost | sort -u > _ch_m	# (word qid)
			merge main _ch_m > _ch_main
			mv _ch_main main
			mktoc main > mtoc
		}
	}

	laptime chkqid_main $t0

	echo '# checking the main if ":" exists or not'
	grep : main|sed 10q

	echo '# checking main if it is really sorted or not'
	chksort main > _ch_main_sort
	laptime chksort_main $t0

	if(test -s _ch_main_sort){
		sed 10q _ch_main_sort
		echo -n 'fix? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y){
			sort -u main > _ch_m
			mv _ch_m main
			mktoc main > mtoc
		}
	}

	laptime done $t0
	echo '# done'
}

fn logupdate {
	ifs=$nl {e=`{rdeventlog}}
	s=$status
	if(~ $s ?*) {
		echo error: $s >[1=2]
		exit error
	}
	if(! ~ $#e 0)
		update -u $e
}

opt=()
while(~ $1 -*){
	opt=$1
	shift
}

# we should clean up _* prior to execution
# otherwise old files may do something bad
if(! ~ $opt -C -F -T)
	rm _* >[2] /dev/null


t0=`{date -n}	# for laptime

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


chkargs $*

switch($opt){
case -b
	build		# build from scratch
	if(! test -e eventlog)
		exit
	updlog
	>eventlog
case -r
	if(~ $#* 0){
		update -r $target
		if(! test -e eventlog)
			exit
		updlog
		>eventlog
	}
	if not
		update -r $*
case -u
	update -u $*	# update only those dirs
case -d
	delete $*	# not tested enough
case -L
	if(! test -e eventlog){
		echo 'no eventlog'
		exit
	}
	# exec in subshell. need to be update log even in case 'no update'
	@{logupdate}
	if(~ $status ?*)
		exit error
	mv _eventlog eventlog	# mv is here! must be before updlog. look updlog
	updlog
case -C
	chkdb
case -S
	stat $target
case -T	# for debug
	awk -F $tab '{print $2}' main > _ch_q_main
	ffm -vf1 -F $tab _ch_q_main qf | grep -v '/$' | awk -F $tab '{print $2}' |\
	9xa extwords -il $wordlen |\
	awk '/:$/{ prev = $0; next }
			{  if(prev && $0 != prev){
					print prev;
					prev = 0;
				}
			}
		'
case *
	usage
}
#rm _*
exit


#######
# NOTE
# if you want to rename one of $target and reflect the result to database
# for example foo to FOO
# 1. rename (mv foo FOO)
# 2. change target in db.conf from foo to FOO
#
