#! /bin/bash
# Generate overview pages for DocServ.
#
# Mandatory parameters:
#   --stitched-config="/path/to/file.xml"    # Full docservconfig file
#                                              (non-positive version)
#   --template-dir="/path/to/templates"
#   --cache-dir="/var/cache/docserv/target"  # Document metadata cache directory
#                                              as generated by docserv script
#   --output-dir="/path/to/output"           # Where to output HTML files
#   --doc-language="ar-ar"                   # Language of the document
#   --ui-languages="en-us de-de"             # Languages that are supported
#                                              by the UI templates
#   --default-ui-language="en-us"            # Default language for the UI in
#                                              case the document language is
#                                              available as a UI language
#   --internal-mode                          # Enable features that are not
#                                              supposed to be shown publically
#
# Optional parameters:
#   --help                                   # Show this help screen

out() {
  >&2 echo -e "$1"
  exit 1
}


me=$(test -L $(realpath $0) && readlink $(realpath $0) || echo $(realpath $0))
mydir=$(dirname $me)

source $mydir/docserv-dirs

app_help() {
  sed -rn '/#!/{n; p; :loop n; p; /^[ \t]*$/q; b loop}' $me | sed -r -e 's/^# ?//' -e "s/\\\$0/$(basename $0)/"
  exit
}

xmllint='xmllint'
jing='jing'
starlet='xmlstarlet'

stylesheet=$share_dir/xslt/buildoverview.xsl
[[ ! -f $stylesheet ]] && out "Stylesheet $stylesheet does not exist.$(readme_message)"

magic_comment='<!--#include docserv_content-->'

stitched_config=

doc_language=
ui_languages=
default_ui_language=

template_dir=
cache_dir=
output_dir=
internal_mode=0

for i in "$@"
  do
    case $i in
      -h|--help)
        app_help
      ;;
      --internal-mode)
        internal_mode=1
      ;;
      --stitched-config=*)
        stitched_config="${i#*=}"
      ;;
      --doc-language=*)
        doc_language="${i#*=}"
      ;;
      --ui-languages=*)
        ui_languages="${i#*=}"
      ;;
      --default-ui-language=*)
        default_ui_language="${i#*=}"
      ;;
      --template-dir=*)
        template_dir="${i#*=}"
      ;;
      --cache-dir=*)
        cache_dir="${i#*=}"
      ;;
      --output-dir=*)
        output_dir="${i#*=}"
      ;;
      *)
        unknown+="  $i\n"
      ;;
    esac
done

[[ "$unknown" ]] && \
  out "There are unknown parameters:\n$unknown"

for lang in "$doc_language" "$ui_languages" "$default_ui_language"; do
  [[ $(echo -e " $lang" | sed -r 's/( [a-z]{2}(-[a-z]{2,5})?)+//') ]] && out "Language parameter ($lang) is not in the right format."
done

for file in "$stitched_config"; do
  [[ ! -f "$file" ]] && out "File $file does not exist."
done

for dir in "$cache_dir/$doc_language" "$template_dir" "$output_dir"; do
  [[ ! -d "$dir" ]] && out "Directory $dir does not exist."
done

template_dir=$(readlink -f $template_dir)
cache_dir=$(readlink -f $cache_dir)
output_dir=$(readlink -f $output_dir)

template_html=$template_dir/template.html
template_translation=$template_dir/translation.xml
template_resources=$template_dir/res

for file in $template_html $template_translation $template_resources; do
  ([[ ! -d "$file" ]] && [[ ! -f "$file" ]]) && out "File/directory $file does not exist."
done

[[ ! $(grep -P '^'"$magic_comment"'$' $template_html) ]] && \
  out "Template $template_html does not include magic comment: $magic_comment"

ui_translation=$(comm -1 -2 <(echo "$doc_language" | tr ' ' '\n' | sort -u | head -1) <(echo -e "$ui_languages" | tr ' ' '\n' | sort -u))
if [[ ! "$ui_translation" ]]; then
  ui_translation=$default_ui_language
fi

temp_dir=$(mktemp -d /tmp/docserv-buildoverview-XXXXXXXX)
intermediate_output=$temp_dir/page.html
cache_file=$temp_dir/cache.xml

output=$output_dir/index.${doc_language}.html
[[ "$doc_language" == "$default_ui_language" ]] && output=$output_dir/index.html

cache_files=$(find "$cache_dir/$doc_language" -name '*.xml')

stitched_cache='<?xml version="1.0" encoding="UTF-8"?>\n<docservcache>\n\n'
for file in $cache_files; do
  stitched_cache+=$($starlet sel -t -c "/document" $file)
  stitched_cache+='\n'
done
stitched_cache+='\n</docservcache>\n'
echo -e "$stitched_cache" > $cache_file


xsltproc \
  --stringparam "template_translation" "$template_translation" \
  --stringparam "cache_file" "$cache_file" \
  --stringparam "doc_language" "$doc_language" \
  --stringparam "ui_translation" "$ui_translation" \
  --stringparam "internal_mode" "$internal_mode" \
  "$stylesheet" \
  "$stitched_config" \
  > "$intermediate_output"

mkdir -p $output_dir/res/
cp -r $template_resources $output_dir

template_top=
template_bottom=

template_lines=$(cat $template_html | wc -l)
template_magic_line=$(grep -nP '^'"$magic_comment"'$' $template_html | cut -f1 -d':')

top_end_line=$(($template_magic_line - 1))
bottom_start_line=$(($template_magic_line + 1))

[[ $top_end_line -gt 0 ]] && template_top=$(head -${top_end_line} $template_html)
[[ $bottom_start_line -le $template_lines ]] && template_bottom=$(tail -n +${bottom_start_line} $template_html)

{
  echo -e "$template_top"
  cat "$intermediate_output"
  echo -e "$template_bottom"
} > "$output"

echo "-> $output_dir"
