#!/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 mkqtd {
	# usage: mkqtd [-r] $target ... > $qtd
	# -r	# recursive
	# now, we don't need sort, because we use ffm
	# NB: du does not sort, so also mkqtd
	# 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:
	#	mkqtd $target | sort -u +t2
	#
	opt=(){
	if(~ $1 -r){
		opt=-r
		shift
	}
	if(~ $#* 0){
		echo 'no argus in mkqtd' >[1=2]
		exit error
	}
	if(~ $opt -r){
		if(~ $#exclude 0){
			du -f $* |unq| awk -F $tab '{print $2}'| 9xa lr -lqQnd0 |\
			awk -F $tab '$4 ~ /^d/ {print $1 "\t" $8 "\t" $9 "/" }'
		}
		if not{		# what should I do if "access permission denied"
			du -f $* |unq| awk -F $tab '{print $2 "/"}' | fgrep -v $exclude |\
			9xa lr -lqQnd0 |\
			awk -F $tab '$4 ~ /^d/ {print $1 "\t" $8 "\t" $9 "/" }'
		}
	}
	if not { # log update
		if(~ $#exclude 0){
			lr -lqQnd1 $* |\
			awk -F $tab '$4 ~ /^d/ {print $1 "\t" $8 "\t" $9 "/" }'
		}
		if not{
			lr -lqQnd1 $* |\
			awk -F $tab '$4 ~ /^d/ {print $1 "\t" $8 "\t" $9 "/" }' |\
			fgrep -vf3 -F $tab $exclude
		}
	}
	}
}

fn build {
	# build from scratch
	# usage: build

	echo $target #DBG

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

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

	mkqtd -r $target > qtd
	mkqp qtd > qd

	awk -F $tab '{print $2}' qd > _d
	mkqdic -b _d > _m
	laptime mkqdic $t0

	sort -u _m > main
	rm _m

	laptime sort $t0

	# you might think that
	# it is better to have only qid dirs (kind/*/*/*) which have wdic of none-zero size.
	# because that makes rdwdic faster.
	# however that also makes our system complicated, so I take simple way.

	mktoc main > mtoc
	laptime done $t0
}

fn update {
	# usage: update [-r|-u] $target
	# update assumes qf,qstf, and main are not broken
	opt=()
	if(~ $1 -*){
		opt=$1
		shift
	}

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

	#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

	# for the temporally, we check qtd and fix it
	# check qtd
	fixqtp1 qtd > _t
	size0=`{fsize qtd}
	size1=`{fsize _t}
	if(test $size0 -ne $size1){
		echo 'dup qid. fixing'
		mv _t qtd
		mkqp qtd > qd
	}

	fixqtp3 qtd > _t
	size0=`{fsize qtd}
	size1=`{fsize _t}
	if(test $size0 -ne $size1){
		echo 'dup dir. fixing'
		mv _t qtd
		mkqp qtd > qd
	}

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

	#
	#	make ready
	#

	> _qtd_update
	> _qtd_rename
	> _q_rm

	if(~ $opt -r){
		mkqtd -r $args > _qtd1	# from real world
		ffm -mf3 -F $tab _args qtd > _qtd0	# old qtd
	}
	if not {
		# this case is update using event log.
		# most of changes come from just updating.
		# some dirs in those $dir might have newly created.
		# and some dirs might have gone.
		# and some dirs might have renamed from other dirs.
		# they are all reflected in event log.
		# here we apply simple way; we define:
		#	_q_qtd: a set of qid in qtd (or qd)
		#   _q_rd: a set of qid of _rd; those are in _q_qtd.
		#   _q_ed: a set of qid of _ed; we can get those qid from
		# 	existing dirs or _q_qtd. they may be different:
		#   qid of newly created dir is not in qtd.
		#	qid of renamed dir is in qtd but the name is older one
		#	qid of just updated dir is in qtd with the same name
		# dirs in _rd consist of removed and renamed(old) files
		#	removed: the qid is in qtd but not in _q_ed
		#	renamed(old): the qid is in qtd and in _q_ed
		# dirs in _ed consist of updated, created, and renamed(new) files
		#	updated: the qid is in qtd. the name is same.
		#	created: the qid is not in qtd
		#	renamed(new): the qid is in qtd. the name is not same.

		# for removed dirs, we should do
		# 1.	remove those name from qtd and qd
		# 2.	remove dirs in dind
		mkqtd $args | sort -u +2 > _qtd1+
		mkqp _qtd1+ > _qd1+
		# we want to have the counter parts: _qtd0+

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

		# 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 '' _qd0+ _qd1+ > _qd+_co		# common parts
		ffm -vf1 -F '' _qd+_co _qd0+ > _qd0r	# the rest (rename)
		ffm -vf1 -F '' _qd+_co _qd1+ > _qd1r	# the rest (rename)
		mkq _qd0r > _q0r
		mkq _qd1r > _q1r
		ffm -f1 -F $tab _q0r _q1r > _q_co
		ffm -f1 -F $tab _q_co _qd0r | sort > _qd0r_co
		ffm -f1 -F $tab _q_co _qd1r | sort > _qd1r_co
		/bin/join -t $tab _qd0r_co _qd1r_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 qtd > _qtd0+	# counter part of _qtd1+
		# discard common lines
		### NB: we cannot discard common lines due to mtime bug of cwfs
		### so we must add _qtd+_co to update
		ffm -f1 -F '' _qtd0+ _qtd1+ > _qtd+_co
		# ffm -vf1 -F '' _qtd+_co _qtd0+ > _qtd0	#BUG
		# ffm -vf1 -F '' _qtd+_co _qtd1+ > _qtd1	#BUG
		# don't stop here!
		# _qtd0 and _qtd1 must cover all relevant names.

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

		awk -F $tab '{print $3}' _qtd0+r > _d0+r
		awk -F $tab '{print $3}' _qtd1+r > _d1+r

		ffm -mf3 -F $tab _d0+r qtd | sort +2 > _qtd0
		if(test -s _tr_map)
			eKR_trans -F $tab _tr_map _qtd0 > _qtd1
		if not
			cat _qtd0 > _qtd1

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

		# time field in _qtf1 is old one. we must fix
		cat _qtd1 _qtd1+r | sort +2 +1 | uniqx -rfF $tab -k 2 > _t
		mv _t _qtd1
		# we restrict to:
		ffm -mf3 -F $tab _d1+r _qtd1 > _t
		mv _t _qtd1

		# let old be (q0,t0,d0) and new be (q1,t1,d1)
		# we can asume t0 < t1 and can discard time info
		# then
		# q0 = q1 and d0 = d1  -> updated
		# q0 = q1 and d0 != d1 -> renamed
		# q0 != q1 and d0 = d1 -> removed and then created
		# names only in (q0,d0) -> removed
		# names only in (q1,d1) -> created
		mkqp _qtd0 > _qd0
		mkqp _qtd1 > _qd1
	}
#exit DBG
	# input: _qtd0  _qtd1
	# fields in _qtd0 and _qtd1 are tab separated.
	# therefore the next two are exact line match.
	ffm -vf1 -F '' _qtd1 _qtd0 > _qtd_gone	# that are only qtd
	ffm -vf1 -F '' _qtd0 _qtd1 > _qtd_new	# that are only current fs
	awk -F $tab '{print $1 "\t" $3}' _qtd_gone > _qd_gone
	awk -F $tab '{print $1 "\t" $3}' _qtd_new  > _qd_new
	ffm -f1 -F '' _qd_gone _qd_new > _qd_comm	# that's updated
	ffm -vf1 -F '' _qd_gone _qd_new > _qd_crrn	# that's created or renamed(to)
	ffm -vf1 -F '' _qd_new _qd_gone > _qd_rmrn	# that's removed or renamed(from)

	mkq _qd_comm > _q_up
	mkq _qd_crrn > _q_crrn
	mkq _qd_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
	### NB: due to mtime bug of cwfs, we must add _qtd+_co to _qtd_update
	# ffm -f1 -F $tab _q_crup  _qtd_new | ffm -mf3 -F $tab _target > _qtd_update
	ffm -f1 -F $tab _q_crup  _qtd_new | ffm -mf3 -F $tab _target > _t
	if(test -s _qtd+_co)
		cat _t _qtd+_co > _qtd_update

	> _qtd_rename
	if(test -s _q_rn){
		# for renaming
		ffm -f1 -F $tab _q_rn  _qtd_new | sort -t $tab > _qtd_rename1	# new
		ffm -f1 -F $tab _q_rn  _qtd_gone | sort -t $tab > _qtd_rename0	# old
		cat _qtd_rename1 > _qtd_rename
	}
	laptime ready $t0
#exit DBG
	# finally:
	mergedb _qtd_update _qtd_rename _q_rm
	laptime done $t0
}

fn delete {
	# usage: delete $dir
	# delete $dir and the subtree from database
	# delete assumes qd,qtd, 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 qtd > _rm_qtd_rm
	awk -F $tab '{print $1}' _rm_qtd_rm > _rm_q

	if(! test -s _rm_q)
		exit

	ffm -vmf3 -F $tab _rm_args qtd > _rm_qtd_rest
	mkqp _rm_qtd_rest > _qd
 
	ffm -vmf2 -F $tab _rm_q main > _main
	mktoc _main > _mtoc

	echo debug: not deleted
	exit

	# real actions are here
	rmqdir -f _rm_q
	mv _mtoc mtoc
	mv _main main
	mv _rm_qtd_rest qtd
	mv _qd qd

	#mkmind main
}


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

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 qtd'
	chkqtp1 qtd > _ch_qtd_dup_q
	if(test -s _ch_qtd_dup_q){
		cat _ch_qtd_dup_q
		echo -n 'fix? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y){
			fixqtp1 qtd > _t
			mv _t qtd
			mkqp qtd > qd
		}
	}

	echo '# checking duplicated path in qtd'
	chkqtp3 qtd > _ch_qtd_dup_path
	if(test -s _ch_qtd_dup_path){
		echo -n 'fix? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y){
			echo 'fixing duplicated path in qtd'
			fixqtp3 qtd > _t
			mv _t qtd
		}
	}

	echo '# checking consistency of qtd to real world'
	mkqtd -r $target > _ch_qtd1
	ffm -vF '' _ch_qtd1 qtd > _ch_qtd00
	ffm -vF '' qtd _ch_qtd1 > _ch_qtd11

	if(test -s _ch_qtd00 || test -s _ch_qtd11) {
		if(test -s _ch_qtd00){
			echo '# dirs that are in qtd but not in real world'
			cat _ch_qtd00
		}
		if(test -s _ch_qtd11) {
			echo '# dirs that are in real world but not in qtd'
			cat _ch_qtd11
		}
		echo -n 'fix? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y){
			cp _ch_qtd1 qtd
			mkqp qtd > qd
		}
	}

	#
	# check the consistency between qtd and existing qdir/*
	# qid and mtime is checked
	#

	# qtd should not have duplicated lines
	awk -F $tab '{print $1 "\t" $2}' qtd |sort > _ck_mq0

	ls -p qdir > _ch_q1
	awk -F $tab '{print $1}' qd > _ch_q0
	ffm -v -F $tab -f1 _ch_q0 _ch_q1 > _ch_q11
	ffm -v -F $tab -f1 _ch_q1 _ch_q0 > _ch_q00	# we need not mind this case

	if(test -s _ch_q11){
		echo '# qids that are in qdir but not in qtd'
		cat _ch_q11
		echo -n 'remove redundant qdir? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y)
			rmqdir -f _ch_q11
	}

	laptime check_qdir $t0

	#
	# index check
	#

	echo '# checking qid in main if they are in qd'
	awk -F $tab '{print $1}' qtd > _ch_q0
	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 qd'
		echo '# only 10 lines are shown below:'
		sed 10q _ch_q0_main
		echo -n 'remove redundant qid in main and remake mtoc? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y){
			mkq qd > _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 Kirara1
	# because mkqdic of old Kiarar1 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 qd | awk -F $tab '{print $2}' |\
	9xa lr -d1 | 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;
				}
			}
		' | sed 's:/[^/]+$:/:g' | sort -u > _ch_d_main_lost
	# example in _ch_d_main_lost
	# /usr/arisawa/bin/rc/photo/
	# they are dirs
	if(test -s _ch_d_main_lost){
		sed 10q _ch_d_main_lost
		echo -n 'fix main and remake mtoc? (Y/n)'
		a=`{read}
		if(~ $#a 0 || ~ $a Y y){
			mkqdic _ch_d_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 the 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'
}

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
	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 $*
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 *error)
		exit error
	mv _eventlog eventlog	# mv is here! must be before updlog. look updlog
	updlog
case -C
	chkdb
case -T	# for debug
	awk -F $tab '{print $2}' main > _ch_q_main
	ffm -vf1 -F $tab _ch_q_main qd | awk -F $tab '{print $2}' |\
	9xa lr -d1 | grep -v '\/$|'$exclude |\
	9xa extwords -idl $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;
				}
			}
		' > _ch_main_lost
	cat _ch_main_lost

case *
	usage
}
#rm _*
exit
