#!/bin/bash
#
# __copy1__
# __copy2__
#
## tools,doc riscostruisce la documentazione da varie fonti
## 
## == usage ==
## 	jtdoc-rebuild
## 
## == descrizione ==
## 
## Il comando esegue una scansione dell'intero albero di progetto,
## estraendo ed elaborando le varie fonti di documentazione riconosciute.
## 
## Le fonti vengono quindi processate e pubblicate nella wiki (Foswiki)
## indicata nella configurazione del progetto.
##
## <!> documentazione incompleta ed in corso di modifica
##
## Appunto: vedere nelle pagine create, su Informazioni, la storia delle
## modifiche (vengono eseguite in automatico dall'utente OsjtoolsBot)
## 
## == formati riconosciuti ==
## 
## Al momento questi sono i formati riconosciuti:
## 
##  * files nella directory $PRJ/docs
##  * files nella directory $PRJ/tmp/docs (temporanei)
##  * scripts shell e perl in $PRJ/bin, con documentazione embedded
##  * documentazione embedded in files di definizioni in formato jtconf
##  (ricercate in base alla variabile di environment $JT_DOCS_SEARCH)
## 
## == formati che si prevede di implementare ==
## 
##  * estrazione doc embedded di altri tipi di scripts
##  * creazione automatica di documenti in base ai dati gia` definiti
##  per il progetto
## 

. jtfunctions.sh

usage()
{
	echo "usage: $CMD" >&2
	exit 1
}


process_file()
{
	local file=$1
	local name=$2
	local section=$3
	local make_index_only=$4
	local offset=1
	local desc=
	local head=
	local wikiname=
	local tpl=
	local tmp=$file.parse.tmp
	local sortsection=

	echo "$file" | grep -q "~$" && return 0		# ignore vi backup files
	echo "$file" | grep -q "\.tmp$" && return 0	# ignore temp files

	[ "$section" == "" ] && {
		head=`head -1 "$file"`
		section=`echo "$head" | sed -e 's/ .*//' -e 's/,/, /g'`
		desc=`echo "$head" | sed -e 's/^[^ ]* //'`
		offset=2
	}
	sortsection=$section
	[ "$section" == "meta" ] && sortsection="00meta"
	echo "$sortsection" | grep -q "^[0-9]" || sortsection="10$sortsection"

	# name normalization
	#
	name=`echo $name | sed -e 's/\.txt//'`
	wikiname="${wiki_prefix}$name"
	wikiname=`echo "$wikiname" | sed -e 's/\./_/g'`

	_jt_valid_wiki_name "$wikiname" || {
		echo " ignore '$file' ($name is not a valid wiki name)" >&2
		return 1
	}

	for tpl in	wiki-$name \
			wiki-`echo "$section" | sed -e 's/,.*//'` \
			wiki-page
	do
		tpl=`_jt_search_template $tpl` && break
	done
	[ "$tpl" ] || {
		_jt_error 1 "can't find template for '$file' (at least 'wiki-page')"
		exit 1
	}

	$make_index_only && {
		echo "$name|$wikiname" >>$file_wiki_dict_index
		echo "$sortsection|$name|$wikiname|$desc" >>$file_wiki_index
		return 0
	}

	echo "# do not modify - autogenerated temp file" >"$FILE_AUTO_WIKI_DICT_TEMP"
	echo "[dict.wiki_auto]"		>>"$FILE_AUTO_WIKI_DICT_TEMP"
	echo "  filename $name"		>>"$FILE_AUTO_WIKI_DICT_TEMP"
	echo "  section $section"	>>"$FILE_AUTO_WIKI_DICT_TEMP"
	echo "  desc $desc"		>>"$FILE_AUTO_WIKI_DICT_TEMP"

	tail -n +$offset $file >$tmp
	jtconf-parse $tmp >/dev/null || {
		local status=$?
		echo -e "\nERROR $status PARSING $file" >&2
		rm -f $tmp
		rm -f "$FILE_AUTO_WIKI_DICT_TEMP"
		return $status
	}

	(
		export BUFFER_BODY=`cat $tmp`
		##log "  processing $file ($wikiname)"
		jtwiki-updatepage $wikiname $tpl || exit $?
	) || exit $?

	echo "$sortsection|$name|$wikiname|$desc" >>$file_wiki_index

	rm -f $tmp "$FILE_AUTO_WIKI_DICT_TEMP"
	return 0
}



process_doc_file()
{
	local file=$1
	local make_index_only=$2

	[ -f "$file" ] || {
		log " ignored '$file' (not a file)"
		continue
	}
	[ -s "$file" ] || {
		log " ignored '$file' (empty)"
		continue
	}

	process_file "$file" "$file" "" $make_index_only || exit $?
}


process_shell_script()
{
	local file=$1
	local make_index_only=$2
	local tmp=/tmp/${CMD}-shell.$$
	local tagmatch="^[ ,	]*##"

	egrep "$tagmatch |$tagmatch$" "$file" | sed \
		-e "s/$tagmatch //" -e "s/$tagmatch$//" >$tmp

	[ -s $tmp ] || {
		rm -f $tmp
		return 0
	}
	[ -s $PRJ/docs/$file ] && {
		echo -e "\n----\n" >>$tmp
		cat $PRJ/docs/$file >>$tmp
	}
	[ -s $PRJ/tmp/docs/$file ] && {
		echo -e "\n----\n" >>$tmp
		cat $PRJ/tmp/docs/$file >>$tmp
	}

	process_file $tmp "$file" "" $make_index_only || {
		echo "warning, errors processing '$file'" >&2
		rm -f $tmp
		exit 1
	}

	rm -f $tmp
}

process_perl_script()
{
	local file=$1
	local make_index_only=$2
	local tmp=/tmp/${CMD}-perl.$$
	local tagmatch="^[ ,	]*##"

	egrep "$tagmatch |$tagmatch$" "$file" | sed \
		-e "s/$tagmatch //" -e "s/$tagmatch$//" >$tmp

	[ -s $tmp ] || {
		rm -f $tmp
		return 0
	}
	[ -s $PRJ/docs/$file ] && {
		echo -e "\n----\n" >>$tmp
		cat $PRJ/docs/$file >>$tmp
	}
	[ -s $PRJ/tmp/docs/$file ] && {
		echo -e "\n----\n" >>$tmp
		cat $PRJ/tmp/docs/$file >>$tmp
	}

	process_file $tmp "$file" "" $make_index_only || {
		echo "warning, errors processing '$file'" >&2
		rm -f $tmp
		exit 1
	}

	rm -f $tmp
	return 0
}


log()
{
	$VERBOSE && echo "$@" >&2
}



# (MAIN)

VERBOSE=true

_jt_set_vars \
	wiki.prefix \
	wiki.index_name \
	|| exit $?

file_wiki_index=$PRJ/lib/auto_wiki_index
file_wiki_dict_index=$PRJ/lib/auto_wiki_dict_index

rm -f $file_wiki_index $file_wiki_dict_index
cp /dev/null $file_wiki_index
cp /dev/null $file_wiki_dict_index

export FILE_AUTO_WIKI_DICT="$PRJ/etc/$PRJNAME/conf.d/auto_wiki_dict"
export FILE_AUTO_WIKI_DICT_INDEX="${FILE_AUTO_WIKI_DICT}_index"
export FILE_AUTO_WIKI_DICT_TEMP="${FILE_AUTO_WIKI_DICT}_temp"

rm -f	"$FILE_AUTO_WIKI_DICT" \
	"$FILE_AUTO_WIKI_DICT_INDEX" \
	"$FILE_AUTO_WIKI_DICT_TEMP"

for make_index_only in true false
do
	if $make_index_only
	then
		log "rebuilding index ..."
	else
		log "processing files ..."
	fi

	for pdir in $PRJ/bin $PRJ/docs $PRJ/tmp/docs `echo $JT_DOCS_SEARCH | tr ':' ' '`
	do
		[ -d $pdir ] || continue

		cd $pdir
		log " processing $pdir ..."

		ls | while read file
		do
			[ -d "$file" ] && continue

			case `file "$file"` in
				*shell*script*)	process_shell_script "$file" $make_index_only ;;
				*perl*script*)	process_perl_script "$file" $make_index_only ;;
				*text|*text,\ *)
					case "$file" in
					 *.txt)	process_doc_file "$file" $make_index_only ;;
					 *)	grep -q "^##" "$file" && \
						   process_shell_script "$file" $make_index_only
						;;
					esac
			esac
		done
	done

	[ -d $PRJ/src/samples ] && {
		cd $PRJ/src/samples
		log " processing $PRJ/src/samples ..."
		find * -type f | while read file
		do
			grep -q "^##" "$file" && process_shell_script "$file" $make_index_only
		done
	}

	$make_index_only && {
		LC_ALL=C sort -u -o $file_wiki_dict_index $file_wiki_dict_index || exit $?
		_jt_start_input_redirect $file_wiki_dict_index
		echo "# do not modify - autogenerated file" >$FILE_AUTO_WIKI_DICT_INDEX
		echo "[dict.wiki_auto]" >>$FILE_AUTO_WIKI_DICT_INDEX
		while read line
		do
			name=`echo "$line" | cut -d'|' -f1`
			wikiname=`echo "$line" | cut -d'|' -f2`
			name=`echo $name | tr '.' '_'`
			echo " $name	[[$wikiname|$name]]"
		done >>$FILE_AUTO_WIKI_DICT_INDEX
		_jt_end_input_redirect
	}
done

[ -s $file_wiki_index ] || exit 1

log -n " sorting index ... "
LC_ALL=C sort -u -o $file_wiki_index $file_wiki_index
set `wc -l $file_wiki_index` 0
log "$1 entries"

prev_section=
index_template=`_jt_search_template wiki-index` || {
	_jt_error 1 "can't find template 'wiki-index'"
	exit 1
}


(
	export PRJ_INFO=`_jt_cat $PRJ/etc/info`
	export BUFFER_BODY=

	_jt_start_input_redirect $file_wiki_index
	while read line
	do
		section=`echo "$line" | cut -d'|' -f1`
		file=`echo "$line" | cut -d'|' -f2`
		name=`echo "$line" | cut -d'|' -f3`
		desc=`echo "$line" | cut -d'|' -f4`

		# toglie eventuale numero (usato per sort) dal nome
		# della sezione
		echo $section | grep -q "^[0-9][0-9]" && {
			section=`echo $section | sed -e 's/^[0-9][0-9]//'`
		}

		[ "$section" != "$prev_section" ] && {
			BUFFER_BODY="$BUFFER_BODY\n== $section ==\n"
			prev_section="$section"
		}
		BUFFER_BODY="$BUFFER_BODY\n * [[$name|$file]] $desc"
	done
	_jt_end_input_redirect

	name=$wiki_prefix$wiki_index_name
	##log "  processing $name ..."
	jtwiki-updatepage $name $index_template || exit $?
)


exit 0
