#!/bin/sh -e
# $0 output_dir format [file ...] [-- argument ...]
# -> pick module according to format
# -> run "module output_dir file arguments" for each file
#     or "module output_dir "." arguments" for no file
#     or "module output_dir format file ... -- arguments" for extras module
# if no module is found, run spec_module output_dir format files -- argument
Me=`basename $0`
Usage="Usage: $Me output_dir format [filename ...] [-- argument ...]"
LibExec="/usr/share/docs-build/docsbuild"

. "$LibExec/modules.sh"

Out=`readlink -e "${1:?No output directory specified
$Usage}" || die "Unexistent output directory $1"`
Format=${2:?"No format specified
$Usage"}
shift; shift;

# run "module output_dir file -- param
#  or "module output_dir -- param if no file
Cut__() { # file [junk] [-- param]
  f=`readlink -e "doc/$1"`; shift
  for Junk
  do
    test "$Junk" = "--" && { shift; break; } ||:
    shift
  done
  "$LibExec/$Module" "$Out" "$f" "$@"
}

Module=`GetModule "$Format"`
test -x "$LibExec/$Module" -a -f "$LibExec/$Module" ||\
    die "$LibExec/$Module module not found, needs for '$Format'."

# Extras module will do the job itself
case "$Module" in
  extra*) "$LibExec/$Module" "$Out" "$Format" "$@";;
  *)
	case "$1" in
	  ""|"--")		# no file specified
	  Cut__ "." "$@" || echo "No default input file specified, build module cannot guess"
	  ;;
	  *)			# some files specified
		for File
		do
		  test "$File" = "--" && break # arguments started
		  Cut__ "$File" "$@" || echo "Input file $File processing failed"
		done
	  ;;
	esac ;;
esac
# Find out the encoding of index.html
INDEXENC=`sed -n '0,/.*[Cc][Hh][Aa][Rr][Ss][Ee][Tt] *= *[^" ]\+".*/s/.*[Cc][Hh][Aa][Rr][Ss][Ee][Tt] *= *\([^" ]\+\)".*/\1/p' "$Out/index.html"`
# convert index.html into UTF8 for future navigation bar addition
if [ -z $INDEXENC ] ; then 
	echo "Warning: index.html: encoding uncpecified, expect cryptic navigation bar"
else
	# replace charset name in index.html
	sed -i '0,/.*[Cc][Hh][Aa][Rr][Ss][Ee][Tt] *= *[^" ]\+".*/s/\(.*[Cc][Hh][Aa][Rr][Ss][Ee][Tt] *=\) *[^" ]\+\(".*\)/\1utf-8\2/' "$Out/index.html"
	iconv -c -f $INDEXENC -t UTF-8 "$Out/index.html" > "$Out/index.html.utf"
	mv "$Out/index.html.utf" "$Out/index.html"
fi
# Addinig navigation bar
echo docs_navigation "$Out/index.html"  "$MODULE_NAV" "$MODULE_ID"
docs_navigation "$Out/index.html"  "$MODULE_NAV" "$MODULE_ID"
