#!/bin/bash

# shellcheck source=start-utils
. "${SCRIPTS:-/}start-utils"
isDebugging && set -x
set -o pipefail

export SERVER="minecraft_server.${VANILLA_VERSION// /_}.jar"

if [ ! -e "$SERVER" ] || [ -n "$FORCE_REDOWNLOAD" ]; then
  log "Downloading $SERVER ..."
  debug "Finding version manifest for $VANILLA_VERSION"
  versionManifestUrl=$(get 'https://launchermeta.mojang.com/mc/game/version_manifest.json' | jq --arg VANILLA_VERSION "$VANILLA_VERSION" --raw-output '[.versions[]|select(.id == $VANILLA_VERSION)][0].url')
  result=$?
  if [ $result != 0 ]; then
    log "ERROR failed to obtain version manifest URL ($result)"
    exit 1
  fi
  if [ "$versionManifestUrl" = "null" ]; then
    log "ERROR couldn't find a matching manifest entry for $VANILLA_VERSION"
    exit 1
  fi
  debug "Found version manifest at $versionManifestUrl"

  serverDownloadUrl=$(get --json-path '$.downloads.server.url' "${versionManifestUrl}")
  result=$?
  if [ $result != 0 ]; then
    log "ERROR failed to obtain version manifest from $versionManifestUrl ($result)"
    exit 1
  elif [ "$serverDownloadUrl" = "null" ]; then
    log "ERROR version $VANILLA_VERSION does not provide a server download"
    exit 1
  fi

  debug "Downloading server from $serverDownloadUrl"
  get -o "$SERVER" "$serverDownloadUrl"
  result=$?
  if [ $result != 0 ]; then
    log "ERROR failed to download server from $serverDownloadUrl ($result)"
    exit 1
  fi
fi

isDebugging && ls -l

exec "${SCRIPTS:-/}start-setupWorld" "$@"
