#!/bin/bash

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

resolveVersion
: "${MOHIST_BUILD:=lastSuccessfulBuild}"

# Docs at https://mohistmc.com/mohistmc-api
mohistApiUrl="https://api.mohistmc.com/project/mohist"
mohistDownloadsPage="https://mohistmc.com/downloadSoftware?project=mohist"

if ! get --exists "${mohistApiUrl}/${VERSION}/builds"; then
  logError "Mohist builds do not exist for ${VERSION}"
  logError "       check ${mohistDownloadsPage} for available versions"
  logError "       and set VERSION accordingly"
  exit 1
fi

if [[ "${MOHIST_BUILD}" == "lastSuccessfulBuild" ]]; then
  # Get the latest build number from the API
  if ! buildNumber=$(
    get --json-path '$[0].id' "${mohistApiUrl}/${VERSION}/builds"
  ); then
    logError "failed to list Mohist builds for ${VERSION}"
    exit 1
  fi
  MOHIST_BUILD="${buildNumber}"
fi

downloadUrl="${mohistApiUrl}/${VERSION}/builds/${MOHIST_BUILD}/download"

if [[ -z "${downloadUrl}" ]]; then
  logError "Could not find build ${MOHIST_BUILD} for version ${VERSION}"
  logError "       check ${mohistDownloadsPage} for available versions"
  logError "       and set VERSION accordingly"
  exit 1
fi

SERVER="/data/mohist-${VERSION}-${MOHIST_BUILD}-server.jar"

if [ ! -f "${SERVER}" ]; then
  log "Downloading Mohist build ${MOHIST_BUILD} for ${VERSION}"
  get -o "${SERVER}" "${downloadUrl}"
fi

export FAMILY=HYBRID
export SERVER

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