#!/bin/bash

. ${SCRIPTS:-/}start-utils
set -o pipefail
set -e

latestAsset=$(
  curl -fsSL https://api.github.com/repos/Luohuayu/CatServer/releases/latest | \
    jq '.assets[] | select(.name | match(".*-universal.jar"))'
)

if [[ -z "${latestAsset}" ]]; then
  log "ERROR: latest release of Catserver is missing universal.jar asset"
  exit 1
fi

isDebugging && log "Latest asset ${latestAsset}"
latestJarName=$(echo ${latestAsset} | jq --raw-output '.name')
latestJarId=$(echo ${latestAsset} | jq --raw-output '.id')


export SERVER="/data/${latestJarName}"

if [ ! -f ${SERVER} ]; then
  log "Downloading ${latestJarName}"
  curl -H "Accept:application/octet-stream" -o "$SERVER" -fsSL https://api.github.com/repos/Luohuayu/CatServer/releases/assets/${latestJarId}
fi

export SKIP_LOG4J_CONFIG=true

# Continue to Final Setup
exec ${SCRIPTS:-/}start-setupWorld "$@"
