# Common part of PO4A wrappers, sourced from gnun-po4a-* scripts.

# Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016,
#   2017, 2018, 2019, 2020,
#   2021, 2022, 2023, 2024 Free Software Foundation, Inc.

# This file is part of GNUnited Nations.

# GNUnited Nations is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# GNUnited Nations 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 General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with GNUnited Nations.  If not, see <http://www.gnu.org/licenses/>.

# Parse the command line.
PO=
master=
flags=
output=

function parse_option () {
  skip_option=
  case "$1" in
      -h* | --help )
	  usage
	  exit 0
	  ;;
      -v* | --version )
	  version
	  exit 0
	  ;;
      --localized )
	  skip_option=yes
	  output="$2"
	  ;;
      --localized=* )
	  output="${1#--localized=}"
          return 0
	  ;;
      --master )
	  skip_option=yes
	  master="$2"
	  ;;
      --master=* )
	  master="${1#--master=}"
          return 0
	  ;;
      --po )
	  skip_option=yes
	  PO="$2"
	  ;;
      --po=* )
	  PO="${1#--po=}"
          return 0
	  ;;
      --format ) # Hardcoded in the generated po4a config.
	  skip_option=yes
	  ;;
      --format=* )
          return 0
	  ;;
  esac
  return 1
}

declare -a flags
i=0

while test $# -ge 1; do
  current_option="$1"
  shift
  if test -n "$current_option"; then
    if parse_option "$current_option" "$1"; then
      continue
    fi
    if test -n "$skip_option"; then
      shift
    else
      flags[$i]="$current_option"
      i=$(($i + 1))
    fi
  fi
done

if test -z "$PO"; then
  echo "$0: no PO file is specified" >&2
  exit 1
fi

if test -z "$master"; then
  echo "$0: no English file is specified" >&2
  exit 1
fi


if test -z "$skip_output"; then
  if test -z "$output"; then
    echo "$0: no output file is specified" >&2
    exit 1
  fi
  lang=${PO%.po}
  lang=${lang##*.}
  POT=${PO%po}pot
  po4a_option=--no-update
else
  po4a_option=--no-translations
  lang=cv
  output=/dev/null
  POT="$PO"
  PO=/dev/null
fi

"$PO4A_BIN" $po4a_option "${flags[@]}" /dev/stdin <<-EOF
	[po4a_langs] $lang
	[po4a_paths] $POT $lang:$PO
	[type: xhtml] $master $lang:$output
EOF
res=$?
test 0 != $res && exit $res # Exit when PO4A fails.
test -z "$skip_output" && exit $res # Don't proceed unless we generate a POT.
if test "$remove_refs" = yes; then
  # At configure time, we didn't find a way to reliably output POT files
  # without source references; remove them with sed.
  "$SED" --in-place '/^#: /d' "$POT"
  exit $?
fi
