#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

: "${PURPUR_BUILD:=LATEST}"
: "${PURPUR_DOWNLOAD_URL:=}"
: "${PURPUR_CONFIG_REPO:=}"

# shellcheck source=start-utils
. "$(dirname "$0")/start-utils"
isDebugging && set -x

resultsFile=/data/.purpur.env

if [[ $PURPUR_DOWNLOAD_URL ]]; then
  if ! mc-image-helper install-purpur \
    --output-directory=/data \
    --results-file="$resultsFile" \
    --url="${PURPUR_DOWNLOAD_URL}"; then
      logError "Failed to download from custom Purpur URL"
      exit 1
  fi
else
  args=(
    --output-directory=/data
    --results-file="$resultsFile"
    --version="$VERSION"
  )
  if [[ $PURPUR_BUILD ]]; then
    args+=(--build="$PURPUR_BUILD")
  fi
  if ! mc-image-helper install-purpur "${args[@]}"; then
      logError "Failed to download Purpur"
      exit 1
  fi
fi

applyResultsFile ${resultsFile}

if [[ "${PURPUR_CONFIG_REPO}" ]]; then
  defaultTopLevelConfigs=(bukkit.yml spigot.yml purpur.yml)
  DOWNLOAD_DEFAULTS=$(buildDownloadList "$PURPUR_CONFIG_REPO" "$VERSION" "${defaultTopLevelConfigs[@]}")
  export DOWNLOAD_DEFAULTS
fi

# Normalize on Spigot for later operations
export FAMILY=SPIGOT

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