#!/bin/bash
# This file is part of GNU TALER.
# Copyright (C) 2014-2023 Taler Systems SA
#
# TALER is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free Software
# Foundation; either version 2.1, or (at your option) any later version.
#
# TALER is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License along with
# TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
#
# @author Florian Dold
# @author Benedikt Muller
# @author Sree Harsha Totakura
# @author Marcello Stanisci
# @author Christian Grothoff
#
#
# Error checking on
set -eu

# defaults
AUTHOR="GNU Taler team"
INPUT="exchange-tos-v0"
OUTPUT=${TALER_EXCHANGE_TERMS_DIR:-$(taler-exchange-config -s "EXCHANGE" -o "TERMS_DIR" -f)}
PAPER="a4"
COPYRIGHT="2014-2025 Taler Systems SA (GPLv3+ or GFDL 1.3+)"

# Parse command-line options
while getopts ':a:C:hi:l:o:p:t:' OPTION; do
  case "$OPTION" in
  a)
    AUTHOR="$OPTARG"
    ;;
  C)
    COPYRIGHT="$OPTARG"
    ;;
  h)
    echo 'Supported options:'
    echo '  -a AUTHOR     -- set author header' "(default: $AUTHOR)"
    echo '  -C COPYRIGHT  -- set copyright header' "(default: $COPYRIGHT)"
    echo '  -h            -- print this help'
    echo '  -i INPUT      -- input file to convert' "(default: $VERSION)"
    echo '  -l LANGUAGE   -- target language to use'
    echo '  -o OUTPUT     -- output directory' "(default: $OUTPUT)"
    echo '  -p PAPER      -- paper format' "(default: $PAPER)"
    echo '  -t TITLE      -- title of the document to generate'
    exit 0
    ;;
  l)
    ADD_LANGUAGE="$OPTARG"
    ;;
  i)
    INPUT="$OPTARG"
    ;;
  o)
    OUTPUT="$OPTARG"
    ;;
  p)
    PAPER="$OPTARG"
    case "$PAPER" in
    a4 | letter) ;;
    *)
      echo "Error: Paper format '$PAPER' invalid (use 'a4' or 'letter')" 1>&2
      exit 1
      ;;
    esac
    ;;
  t)
    TITLE="$OPTARG"
    ;;
  ?)
    echo "Unrecognized command line option" 1>&2
    exit 1
    ;;
  esac
done

# Throw away arguments already processed by getopt
shift $(($OPTIND - 1))

if [ ! -z "${1:-}" ]
then
  echo "Error: Superfluous arguments given on command line ($@)." 1>&2
  exit 1
fi

if ! which pandoc >/dev/null; then
  echo "Command 'pandoc' not found, but required. Please install pandoc." 1>&2
  exit 1
fi

# FIXME: do we actually need 'gs'?
if ! which gs >/dev/null; then
  echo "Command 'gs' not found, but required. Please install ghostscript." 1>&2
  exit 1
fi

if ! which pdfroff >/dev/null; then
  echo "Command 'pdfroff' not found, but required. Please install pdfroff/groff." 1>&2
  exit 1
fi

# Sometimes we just want the basename, not the directory.
INPUT_BASENAME=$(basename "${INPUT}")

# We append ".$LANG.rst" as needed, remove if given on command-line
# shellcheck disable=SC2001
if [ -z "${ADD_LANGUAGE:-}" ]
then
    # Language not specified, check if INPUT provides a hint:
    echo $INPUT_BASENAME
    if echo "${INPUT_BASENAME}" | grep -e '\...\.rst$' >/dev/null;
    then
        # Extract language from basename
        ADD_LANGUAGE=$(echo "${INPUT_BASENAME}" | awk -F . '{print $2}')
    else
        # Default to English
        ADD_LANGUAGE="en"
    fi
fi


# We append ".$LANG.rst" as needed, remove to get VERSION if given on command-line
# shellcheck disable=SC2001
VERSION=$(echo "${INPUT_BASENAME}" | sed -e "s/\...\.rst$//")

# In case absolute path is given for the input, keep that as well
INPUT_DIRNAME=$(dirname "${INPUT}")

if ! echo "${ADD_LANGUAGE}" | grep -e '^..$' >/dev/null;
then
    echo "Error: Invalid language '${ADD_LANGUAGE}'. Two characters (en, de, fr, ...) expected." 1>&2
    exit 1
fi

# Find input file
if [ ! -f "${INPUT_DIRNAME}/${VERSION}.${ADD_LANGUAGE}.rst" ];
then
    # Try with default installation path
    if [ "." = "${INPUT_DIRNAME}" ]
    then
        # Try again with default system path
        INPUT_DIRNAME="/usr/share/taler-exchange/terms"
    else
        echo "Error: File '${INPUT_DIRNAME}/${VERSION}.${ADD_LANGUAGE}.rst' not found. Please check '-i' option." 1>&2
        exit 1
    fi

    if [ ! -f "${INPUT_DIRNAME}/${VERSION}.${ADD_LANGUAGE}.rst" ];
    then
        echo "Error: File '${INPUT_DIRNAME}/${VERSION}.${ADD_LANGUAGE}.rst' not found. Please check '-i' option." 1>&2
        exit 1
    fi
fi

BUILDFILE_RST="${INPUT_DIRNAME}/${VERSION}.${ADD_LANGUAGE}.rst"

if [ -z ${TITLE+x} ];
then
  TITLE=$(head -n1 "$BUILDFILE_RST")
  echo "Title automatically set to '$TITLE'" 1>&2
fi

# shellcheck disable=SC2086
echo "Generating files at '$OUTPUT' for version '$VERSION' and language '${ADD_LANGUAGE}':" 1>&2

mkdir -p "${OUTPUT}/${ADD_LANGUAGE}/"

OUTBASE="${OUTPUT}/${ADD_LANGUAGE}/${VERSION}"

echo "$VERSION MD ($ADD_LANGUAGE)..." 1>&2
pandoc \
    -i "$BUILDFILE_RST" \
    -o "${OUTBASE}.md" \
    --pdf-engine=pdfroff \
    --variable=title:"$TITLE" \
    --variable=lang:"$ADD_LANGUAGE" \
    --variable=author:"$AUTHOR" \
    --variable=rights:"$COPYRIGHT" \
    --shift-heading-level-by=-1

echo "$VERSION PDF ($ADD_LANGUAGE)..." 1>&2
pandoc \
    -i "$BUILDFILE_RST" \
    -o "${OUTBASE}.pdf" \
    --pdf-engine=pdfroff \
    --variable=title:"$TITLE" \
    --variable=lang:"$ADD_LANGUAGE" \
    --variable=author:"$AUTHOR" \
    --variable=rights:"$COPYRIGHT" \
    --variable=papersize:"$PAPER" \
    --shift-heading-level-by=-1

echo "$VERSION HTML ($ADD_LANGUAGE)..." 1>&2
# FIXME: Newer versions of pandic should use
# --embed-resources --standalone instead of --self-contained
pandoc \
    -i "$BUILDFILE_RST" \
    -o "${OUTBASE}.html" \
    --variable=title:"$TITLE" \
    --variable=lang:"$ADD_LANGUAGE" \
    --variable=author:"$AUTHOR" \
    --variable=rights:"$COPYRIGHT" \
    --self-contained \
    --shift-heading-level-by=-1

echo "$VERSION TXT ($ADD_LANGUAGE)..." 1>&2
pandoc \
    -i "$BUILDFILE_RST" \
    -o "${OUTBASE}.txt"

echo "Done" 1>&2
exit 0
