#!/bin/false

# Shared variables and functions for java and cpp generator scripts
fatal_error() {
  echo "$@" >&2
  exit 1
}

# RPG_LANG has to be set before sourcing this file
if [[ -z ${RPG_LANG} ]]; then
  fatal_error "Error: internal-generate-shared.sh sourced without declaring RPG_LANG"
fi

# Get the root directory.

# Relative paths are converted to absolute paths.
ROOT_DIR=$(dirname ${0:?})
if [[ "${ROOT_DIR:0:1}" != "/" ]]
then
  ROOT_DIR=$(pwd)/${ROOT_DIR:?}
fi
ROOT_DIR=${ROOT_DIR:?}/.. 

# Check that profile name was given and exists
# Also, if missing, create empty expected-durations.conf, as the default profiles expect it
check_profile() {
  PROFILE_NAME=${1}
  if [[ -z ${PROFILE_NAME} ]]
  then
    fatal_error "Error: Expecting profile name on the command line."
  fi
  PROFILE_FILE=${ROOT_DIR:?}/bin/conf/${RPG_LANG}/${PROFILE_NAME:?}.conf
  if [[ ! -f ${PROFILE_FILE} ]]
  then
    fatal_error "Error: Profile ${PROFILE_FILE} not found."
  fi

  local EXPECTED_DURATIONS="${ROOT_DIR:?}/bin/conf/${RPG_LANG}/expected-durations.conf"
  # if missing, create empty expected-durations.conf, as the default configs expect it
  [[ -f "${EXPECTED_DURATIONS}" ]] || touch "${EXPECTED_DURATIONS}" 
}

# We either accept the output directory on the command
# line, or create a temporary one if none is given.
create_data_dir() {
  DATA_DIR=${1}
  if [[ -z ${DATA_DIR} ]]
  then
    DATA_DIR=$(mktemp -d rpg.XXXXXXXX)
  else
    if ! mkdir ${DATA_DIR:?}
    then
      fatal_error "Error: Target directory already exists."
    fi
  fi
}

# Extract a simple id;name;classname file (for R) from the architecture xml description
parse_modules() {
  ${ROOT_DIR}/bin/utils/parse-modules.py ${1} > ${2}
}

# If xmllint or htmltidy is available, indent the main.xml architecture description.
html_tidy() {
  if [[ -n "$(which xmllint 2>/dev/null)" ]]
  then
    xmllint --format "${1}" --output "${1}"
  elif [[ -n "$(which tidy 2>/dev/null)" ]]
  then
    tidy -q -xml -i -o "${1}" "${1}"
  fi
}

