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

. "$(dirname "$0")/start-utils"
isDebugging && set -x

: "${LIMBO_BUILD:=LATEST}"
: "${FORCE_REDOWNLOAD:=false}"
: "${LIMBO_SCHEMA_FILENAME:=default.schem}"
: "${LEVEL:=default;${LIMBO_SCHEMA_FILENAME}}"
# defaults to localhost, if this is not set
: "${SERVER_IP:=0.0.0.0}"

export LEVEL SERVER_IP

if [[ ${LIMBO_BUILD^^} == LATEST ]]; then
  LIMBO_BUILD=lastStableBuild
fi

baseUrl="https://ci.loohpjames.com/job/Limbo/${LIMBO_BUILD}"
buildInfoUrl="${baseUrl}/api/json"
buildJson=$(curl -fsSL "${buildInfoUrl}")
if [ $? != 0 ]; then
  logError "Failed to get build info from ${buildInfoUrl} (status=$?)"
  exit 1
fi

if [[ ${LIMBO_BUILD} = lastStableBuild ]]; then
  LIMBO_BUILD=$(jq -r '.number' <<<${buildJson})
  log "Resolved latest Limbo build to ${LIMBO_BUILD}"
fi

getRelativePath() {
  local pattern=$1
  jq -r --arg pattern "$pattern" '.artifacts[] | select(.fileName|test($pattern)) | .relativePath' <<<${buildJson}
}

artifactPath=$(getRelativePath "^Limbo-")
defaultSchemaPath=$(getRelativePath ".*\\.schem")

export SERVER="limbo-${LIMBO_BUILD}.jar"

if [ ! -f "$SERVER" ] || isTrue "$FORCE_REDOWNLOAD"; then
    downloadUrl="${baseUrl}/artifact/${artifactPath}"
    log "Downloading Limbo from $downloadUrl ..."
    if ! curl -fsSL -o "$SERVER" "$downloadUrl"; then
      logError "Failed to download from $downloadUrl (status=$?)"
      exit 3
    fi

fi

if [ ! -f "${LIMBO_SCHEMA_FILENAME}" ]; then
  log "Downloading default schem file"
  if ! curl -o "${LIMBO_SCHEMA_FILENAME}" -fsSL "${baseUrl}/artifact/${defaultSchemaPath}"; then
      logError "Failed to download schema file $baseUrl (status=$?)"
      exit 3
  fi
fi

if [[ ${LEVEL} != *\;* ]]; then
  LEVEL="${LEVEL};${LIMBO_SCHEMA_FILENAME}"
fi
export LEVEL

export FAMILY=LIMBO
exec "$(dirname "$0")/start-setupWorld" "$@"
