#!/bin/bash
set -eu

# shellcheck source=start-utils
. "$(dirname "$0")/start-utils"

resultsFile=/data/.install-modrinth.env

: "${MODRINTH_MODPACK:=${MODRINTH_PROJECT:-}}"
: "${MODRINTH_LOADER:=}"
: "${MODRINTH_VERSION:=${MODRINTH_VERSION_ID:-}}"
: "${MODRINTH_IGNORE_MISSING_FILES=}"
: "${MODRINTH_EXCLUDE_FILES=}"
: "${MODRINTH_FORCE_INCLUDE_FILES=}"
: "${MODRINTH_OVERRIDES_EXCLUSIONS=}"
: "${MODRINTH_DEFAULT_EXCLUDE_INCLUDES=/image/modrinth-exclude-include.json}"
: "${MODRINTH_FORCE_MODLOADER_REINSTALL:=${FORCE_MODLOADER_REINSTALL:-false}}"

if [[ ! $MODRINTH_MODPACK ]]; then
  logError "MODRINTH_MODPACK must be set when using TYPE/MODPACK_PLATFORM/MOD_PLATFORM of MODRINTH"
  exit 1
fi

isDebugging && set -x

ensureRemoveAllModsOff "MODPACK_PLATFORM=MODRINTH"

args=(
  --results-file="$resultsFile"
  --project="${MODRINTH_MODPACK}"
  --output-directory=/data
)

if [[ $MODRINTH_IGNORE_MISSING_FILES ]]; then
  args+=(--ignore-missing-files "$MODRINTH_IGNORE_MISSING_FILES")
fi
if isTrue "${MODRINTH_FORCE_MODLOADER_REINSTALL}"; then
  args+=(--force-modloader-reinstall)
fi

case "${VERSION^^}" in
  LATEST)
    # need to be backward compatible with old variable name, MODRINTH_DEFAULT_VERSION_TYPE
    : "${MODRINTH_MODPACK_VERSION_TYPE:=${MODRINTH_DEFAULT_VERSION_TYPE:-release}}"
    ;;
  SNAPSHOT)
    : "${MODRINTH_MODPACK_VERSION_TYPE:=${MODRINTH_DEFAULT_VERSION_TYPE:-beta}}"
    ;;
  *)
    : "${MODRINTH_MODPACK_VERSION_TYPE:=${MODRINTH_DEFAULT_VERSION_TYPE:-release}}"
    args+=("--game-version=$VERSION")
    ;;
esac

setArg() {
  arg="${1?}"
  var="${2?}"

  if [[ ${!var} ]]; then
      args+=("${arg}=${!var}")
  fi
}
setArg --loader MODRINTH_LOADER
setArg --version MODRINTH_VERSION
setArg --default-version-type MODRINTH_MODPACK_VERSION_TYPE
setArg --exclude-files MODRINTH_EXCLUDE_FILES
setArg --force-include-files MODRINTH_FORCE_INCLUDE_FILES
setArg --overrides-exclusions MODRINTH_OVERRIDES_EXCLUSIONS
setArg --default-exclude-includes MODRINTH_DEFAULT_EXCLUDE_INCLUDES

if ! mc-image-helper install-modrinth-modpack "${args[@]}"; then
    logError "Failed to installModrinth modpack"
    exit 1
fi

applyResultsFile ${resultsFile}
resolveFamily

exec "$(dirname "$0")/start-setupWorld" "$@"
