#!/usr/bin/env bash


# Default values
LANGUAGE="en"
SECTION_SEARCH=""

# Valid language codes
valid_languages=("en" "pl" "es" "fr" "ua" "ru" "cs" "he" "de")

# Function to print usage information
usage() {
  echo "Usage: $0 [language] [-p|--printable] [-n|--no-bg] [-s|--section SEARCH]"
  echo "Example: $0 fr --printable --no-bg"
  echo
  echo "Positional arguments:"
  echo "  language           Language code (${valid_languages[*]})"
  echo "                     Defaults to 'en' if not specified"
  echo
  echo "Options:"
  echo "  -p, --printable    Enable printable mode"
  echo "  -n, --no-bg        Disable background"
  echo "  -s, --section      Build a single section matching the input given"
  exit 1
}

# Function to check if language is valid
is_valid_language() {
  local lang="$1"
  for valid_lang in "${valid_languages[@]}"; do
    if [[ "$lang" = "$valid_lang" ]]; then
      return 0
    fi
  done
  return 1
}

# Check if first argument is a language code
if [[ $1 =~ ^[a-z]{2}$ ]]; then
  if is_valid_language "$1"; then
    LANGUAGE="$1"
    shift
  else
    echo "Error: Invalid language code '$1'. Valid codes are: ${valid_languages[*]}" >&2
    exit 1
  fi
fi

# Parse remaining command line arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    -p|--printable)
        export HOMM3_PRINTABLE=1
        shift
        ;;
    -n|--no-bg)
        export HOMM3_NO_ART_BACKGROUND=1
        shift
        ;;
    -s|--section)
        shift
        if [[ $# -lt 1 ]]; then
          echo "Error: -s|--section requires a string argument" >&2
          usage
        fi
        SECTION_SEARCH="$1"
        shift
        ;;
    -h|--help)
        usage
        ;;
    -*)
        echo "Error: Unknown option $1" >&2
        usage
        ;;
    *)
        echo "Error: Unexpected argument '$1'" >&2
        usage
        ;;
  esac
done

case "$(uname -s)" in
  Darwin*)    open=open;;
  Linux*)     open=xdg-open;;
esac


case "${LANGUAGE}" in
  ru|ua|cs|he)
    ENGINE=-pdflua
    ;;
  *)
    ENGINE=-pdf
    ;;
esac

if [[ -n "${SECTION_SEARCH}" ]]; then
  TARGET=$(grep "include{" structure.tex | grep "$SECTION_SEARCH")

  # Target is empty
  if [[ -z "$TARGET" ]]; then
    echo "Error: No section found matching '$SECTION_SEARCH'" >&2
    exit 1
  fi

  # Target is ambiguous
  if [[ $(echo "$TARGET" | wc -l) -gt 1 ]]; then
    echo "Error: Multiple sections found matching '$SECTION_SEARCH':" >&2
    echo "$TARGET" >&2
    exit 1
  fi

  echo "$TARGET" > structure.tex
fi

cleanup() {
  if [[ -n "${SECTION_SEARCH}" ]]; then
    git restore structure.tex
  fi
  if [[ ${LANGUAGE} != en ]]; then
    git restore po4a.cfg
  fi
}

trap cleanup EXIT

if [[ ${LANGUAGE} != en ]]; then
  # limit output to specified language
  sed -i'' "s/^\[po4a_langs\].*$/[po4a_langs] ${LANGUAGE}/" po4a.cfg
  if ! po4a --no-update po4a.cfg \
       2> >(grep -v "unmatched end of environment .multicols\| (po4a::tex)$" >&2) \
       | grep "/${LANGUAGE}/"; then

    echo -e "---\npo4a failed for language ${LANGUAGE}, please fix the errors."

    find translations -name "$LANGUAGE.po" -type f -exec msgfmt -c --check-format -o /dev/null '{}' \;

    exit 1
  fi
fi

# rm triggers latexmk build even if previous artifacts generated by faulty run of po4a prevent it from running
rm -f "main_${LANGUAGE}.aux" && \
  latexmk ${ENGINE} -shell-escape "main_${LANGUAGE}.tex"
${open} "main_${LANGUAGE}.pdf" &> /dev/null &

# Optimize PDF if it's a single section and ghostscript is available
if [[ -n "${SECTION_SEARCH}" ]] && command -v gs >/dev/null 2>&1; then
  tools/optimize.sh "${LANGUAGE}"
  mv "main_${LANGUAGE}_optimized.pdf" "main_${LANGUAGE}.pdf"
fi

echo "main_${LANGUAGE}.pdf"
