#!/bin/rc
rfork e

usage='usage: kfind2 [-G][-t db]  pattern
pattern: regular expression pattern
-G: don''t output G and the pattern'

#kirara2=/n/other/kirara2
if(~ $#kirara2 0){
	echo set '$kirara2' >[1=2]
	exit
}
kirara=$kirara2
. $kirara/kirara.conf
path=(/bin/kirara /bin)

sp=' '
tab='	'
nl='
'

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

reg=no
nog=no

#	a generic routine to regulate arguments
#	NB: options that are followed by string is not supported
a=()
while(~ $1 -*){
	switch($1){
	case -
	echo $usage >[1=2]
	exit
	case -?
	a=($a $1)
	shift
	case -??*
	a=($a `{echo $1 | sed s/-//|sed 's/[a-zA-Z]/-& /g'})
	shift
	}
}
*=($a $*)

kdb=()
while(~ $1 -*){
	switch($1){
	case -G
	nog=yes
	shift
	case -t
	shift
	kdb=($kdb $kirara/$1^db)
	shift
	case -*
	echo $usage >[1=2]
	exit
	}
}

if(! ~ $#* 1){
	echo $usage >[1=2]
	exit
}

fn chkpattern {
	p=$1 e=() {
	# check the pattern
	if(echo $p | grep -s '[!-%''()+-/:->@[-^`{}~]'){
		echo 'unallowed symbol in the pattern' >[1=2]
		exit
	}
	e=''
	for(x in `{seq 1 $wordlen})
		e=$e'[^*?|]'
	if(echo $p | grep -sv '(^| |&)'$e){
		echo 'pattern must begin with two or more regular letters' >[1=2]
		exit
	}
	}
}

fn xind {
	# usage: xind $patt
	# $patt is regexp with '|'.
	# decompose by '|'
	# and extract first two chars from them and search mtoc
	# don't echo to stdout for debug
	p=() q=() r=() s=(){
	ifs='|' {r=`{echo $1}}	# decompose by '|'
	for(s in $r){
		p=`{echo $s | awk -v 'wordlen='$wordlen '{print substr($0,1,wordlen)}'}
		q=`{fgrep -gf1 -F $sp $p mtoc}
		if(! ~ $#q 0)
			ftrim -s $q(2) -e $q(3) main
	}
	}
}

fn find {
	p=() q=$* r=() {
	#echo '#$q' $q >[1=2]	#DBG
	# DBG: example of $1 is ('abc|def78' 'ef12ax|ghi')
	p=`{echo $q(1) | sed 's/\|/*|/g'}
	#echo '#$q(1)' $q(1) >[1=2]	#DBG
	xind $q(1) | fgrep -gf1 -F $tab $q(1) | awk '{print $2}' | sort -u > /tmp/_kf_c
	if(! test -s /tmp/_kf_c)
		exit
	q=$q(2-)
	for(r in $q){
		xind $r | fgrep -gf1 -F $tab $r | awk '{print $2}' | sort -u | comm -12 /tmp/_kf_c - > /tmp/_kf_c1
		mv /tmp/_kf_c1 /tmp/_kf_c
		if(! test -s /tmp/_kf_c)
			exit
	}
	cat /tmp/_kf_c
	#rm /tmp/_kf_* >[2] /dev/null
	}
}

chkpattern $1
ifs=$nl {q=`{echo $1 | tr '&' '|'}}
ifs=$nl {p=`{echo $1 | tolower}}
p=`{echo $p | tr '&' ' '}
#echo '#p' $#p $p >[1=2]	#DBG

if(~ $#kdb 0)
	kdb=$kirara/*db

for(db in $kdb){
	if(~ $nog yes) # no -G option. path per line. don't convert to quote format
		@{cd $db && find $p | KR_trans qf | sort -u}
	if not {
		@{cd $db && find $p | KR_trans -F $tab qf | sort -u |\
		awk -F $tab -v 'query='$q '
		function quote(s){ gsub("''","''''", s); return "''" s "''" }
		# special charactors for shell(rc) that should be quoted
		/[ |&[\]*?;$^={}@#()`<>'']/ {print "G2","''" query "''",quote($0); next}
		{print "G2","''" query "''",$0}
		'}
	}
}
