#!/bin/bash
set -eu

# shellcheck source=start-utils
. "${SCRIPTS:-/}start-utils"

: "${QUILT_LAUNCHER:=}"
: "${QUILT_LAUNCHER_URL:=}"
: "${QUILT_INSTALLER_URL:=}"
: "${QUILT_INSTALLER_VERSION:=LATEST}"
: "${QUILT_LOADER_VERSION:=LATEST}"

isDebugging && set -x

resultsFile=/data/.quilt.env

if [[ $QUILT_LAUNCHER ]]; then
  log "WARNING: use of QUILT_LAUNCHER is a deprecated feature."
  SERVER="$QUILT_LAUNCHER"
  export SERVER
  resolveVersion

  export FAMILY=FABRIC
  exec "${SCRIPTS:-/}start-setupWorld" "$@"

elif [[ $QUILT_LAUNCHER_URL ]]; then
  log "ERROR: QUILT_LAUNCHER_URL is not longer supported. Pre-download and use QUILT_LAUNCHER."
  exit 2

elif [[ $QUILT_INSTALLER_URL ]]; then
  if ! mc-image-helper install-quilt \
    --loader-version="$QUILT_LOADER_VERSION" \
    --minecraft-version="$VERSION" \
    --output-directory=/data \
    --results-file="$resultsFile" \
    --installer-url="$QUILT_INSTALLER_URL"; then
    log "ERROR: failed to install Quilt given custom installer URL $QUILT_INSTALLER_URL"
    exit 2
  fi

else
  if ! mc-image-helper install-quilt \
    --loader-version="$QUILT_LOADER_VERSION" \
    --minecraft-version="$VERSION" \
    --output-directory=/data \
    --results-file="$resultsFile" \
    --installer-version="$QUILT_INSTALLER_VERSION"; then
    log "ERROR: failed to install Quilt given installer version $QUILT_INSTALLER_VERSION"
    exit 2
  fi

fi

# grab SERVER, VERSION and export it
set -a
# shellcheck disable=SC1090
source "${resultsFile}"
set +a

export FAMILY=FABRIC
exec "${SCRIPTS:-/}start-setupWorld" "$@"
