#!/bin/bash

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

resolveVersion
: "${CRUCIBLE_RELEASE:=latest}"

# An omitted --release-tag means the latest release, so only pass it when a
# specific release was requested
crucibleReleaseArgs=()
[[ ${CRUCIBLE_RELEASE} == latest ]] || crucibleReleaseArgs+=(--release-tag="${CRUCIBLE_RELEASE}")

crucibleRepo=CrucibleMC/Crucible

log "Downloading Crucible ${VERSION} from the ${CRUCIBLE_RELEASE} release"
if ! SERVER=$(mc-image-helper github download-asset \
  "${crucibleReleaseArgs[@]}" \
  --output-directory=/data \
  --name-pattern="^Crucible-${VERSION}-.+\.jar$" \
  ${crucibleRepo}
  ); then
  logError "Failed to download Crucible jar for ${VERSION} from the ${CRUCIBLE_RELEASE} release"
  logError "Ensure CRUCIBLE_RELEASE is one of the releases at ${crucibleReleasesUrl}"
  exit 1
fi

librariesDir=/data/libraries
if [ ! -d "$librariesDir" ]; then
  if ! librariesZip=$(mc-image-helper github download-asset \
    "${crucibleReleaseArgs[@]}" \
    --output-directory=/tmp \
    --name-pattern="^libraries\.zip$" \
    ${crucibleRepo}
    ); then
    logError "Failed to download Crucible libraries from the ${CRUCIBLE_RELEASE} release"
    exit 1
  fi

  log "Downloading Crucible libraries"
  if ! unzip "$librariesZip" -d "$librariesDir"; then
    logError "Failed to unzip Crucible libraries"
    exit 1
  fi
  rm "$librariesZip"
fi

export SERVER
export FAMILY=HYBRID
export HYBRIDTYPE=forge

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