#!/usr/bin/env bash
###############################################################################
# BRLTTY - A background process providing access to the console screen (when in
#          text mode) for a blind person using a refreshable braille display.
#
# Copyright (C) 1995-2026 by The BRLTTY Developers.
#
# BRLTTY comes with ABSOLUTELY NO WARRANTY.
#
# This is free software, placed under the terms of the
# GNU Lesser General Public License, as published by the Free Software
# Foundation; either version 2.1 of the License, or (at your option) any
# later version. Please see the file LICENSE-LGPL for details.
#
# Web Page: http://brltty.app/
#
# This software is maintained by Dave Mielke <dave@mielke.cc>.
###############################################################################

. "`dirname "${0}"`/../brltty-prologue.bash"

showProgramUsagePurpose() {
cat <<END_OF_PROGRAM_USAGE_PURPOSE
Convert a document from reStructured text to plain text with some simple markup.
END_OF_PROGRAM_USAGE_PURPOSE
}

showProgramUsageNotes() {
cat <<END_OF_PROGRAM_USAGE_NOTES
If the input file is specified as a minus sign (-) then reStructured text is read from standard input.
Likewise, if the output file is specified as a minus sign (-) then plain text is written to standard output.

Some simple markup is added to the plain text:
  [# document header #]
  # level 1 header #
  ## level 2 header ##
  ### level 3 header ###
  [internal reference text]
  [external reference text] {URL}
  <-- Table - caption text -->
  **bold text**
  <italic text>
  __underlined text__
  \`literal text\`
  "quoted text"
  ~~strike text~~
  ^(superscript text)
  _(subscript text)

  <\`\`\`
  literal block
  \`\`\`>

  <"""
  block quote
  """>
END_OF_PROGRAM_USAGE_NOTES
}

htmlFile="${programName}.html"
rstFormat=rst
inputFormat="${rstFormat}"

declare -a inputExtensionsList=()
declare -A inputFormatsArray=()

defineInputExtension() {
   local extension="${1}"
   local format="${2}"

   inputFormatsArray["${extension}"]="${format}"
   inputExtensionsList+=("${extension}")
}

defineInputExtension csv csv
defineInputExtension db docbook
defineInputExtension docbook docbook
defineInputExtension docx docx
defineInputExtension epub epub
defineInputExtension htm html
defineInputExtension html html
defineInputExtension json json
defineInputExtension man man
defineInputExtension md markdown
defineInputExtension odt odt
defineInputExtension rst rst
defineInputExtension rtf rtf
defineInputExtension tex latex
defineInputExtension tsv tsv

inputExtensionsString="${inputExtensionsList[*]}"
inputExtensionsString="${inputExtensionsString// /, }"

addProgramOption k flag keepHTML "keep the intermediate HTML document as ${htmlFile}"
addProgramOption x flag useInputExtension "use the extensiin of the input file to determine the input format - supported extensions are: ${inputExtensionsString}"
addProgramParameter input inputFile "an existing document formatted as reStructured text"
addProgramParameter output textFile "where to write the plain text document"
parseProgramArguments "${@}"

pandocFormat=""
pandocOptions=()
pandocOptions+=(--lua-filter "${programPath}.lua")

[ "${inputFile}" = "-" ] || {
   verifyInputFile "${inputFile}"

   "${useInputExtension}" && {
      inputName="${inputFile##*/}"
      inputExtension="${inputName##*.}"

      [ "${inputExtension}" = "${inputName}" ] || {
         verifyChoice "input file extension" inputExtension "${!inputFormatsArray[@]}"
         inputFormat="${inputFormatsArray["${inputExtension}"]}"
      }
   }
}

[ "${textFile}" = "-" ] || {
   verifyOutputFile "${textFile}"
   pandocOptions+=(--output "${textFile}")
}

if "${keepHTML}"
then
   verifyOutputFile "${htmlFile}"
else
   needTemporaryDirectory
   htmlFile="${temporaryDirectory}/${htmlFile}"
fi

set -e
cd "${initialDirectory}"

if [ "${inputFormat}" = "${rstFormat}" ]
then
   rst2html --config "${programDirectory}/docutils.conf" -- "${inputFile}" "${htmlFile}"
   pandocInput="${htmlFile}"
   pandocFormat="html"
else
   pandocInput="${inputFile}"
   pandocFormat="${inputFormat}"
fi

pandocOptions+=(--from "${pandocFormat}")
pandocOptions+=(--to plain)

export LUA_PATH="${programDirectory}/../?.lua;;"
pandoc "${pandocOptions[@]}" -- "${pandocInput}"
exit 0
