#!/bin/bash

: "${CLEANROOM_FORCE_REINSTALL:=false}"

# shellcheck source=start-utils
. "${SCRIPTS:-$(dirname "$0")}/start-utils"
isDebugging && set -x
resultsFile=/data/.run-cleanroom.env

declare -a cleanroom_installer_options
cleanroom_installer_options+=(--output-directory=/data)
cleanroom_installer_options+=(--results-file="${resultsFile}")
cleanroom_installer_options+=(--force-reinstall="${CLEANROOM_FORCE_REINSTALL}")

if [[ ${CLEANROOM_LOADER_VERSION} ]]; then
  cleanroom_installer_options+=(--loader-version="${CLEANROOM_LOADER_VERSION}")
fi

if [[ ${CLEANROOM_INSTALLER_VERSION} ]]; then
  cleanroom_installer_options+=(--installer-version="${CLEANROOM_INSTALLER_VERSION}")
fi

if [[ ${CLEANROOM_FROM_FILE} ]]; then
  cleanroom_installer_options+=(--from-local-file="${CLEANROOM_FROM_FILE}")
fi

if [[ ${CLEANROOM_FROM_URL} ]]; then
  cleanroom_installer_options+=(--from-url="${CLEANROOM_FROM_URL}")
fi

if [[ ${CLEANROOM_MAVEN_URL} ]]; then
  cleanroom_installer_options+=(--cleanroom-maven-url="${CLEANROOM_MAVEN_URL}")
fi

if ! mc-image-helper install-cleanroom "${cleanroom_installer_options[@]}" ; then
    if [[ ${CLEANROOM_FROM_FILE} ]]; then
      logError "Failed to install Cleanroom given installer ${CLEANROOM_FROM_FILE}"
    elif [[ ${CLEANROOM_FROM_URL:-} ]]; then
      logError "Failed to install Cleanroom from ${CLEANROOM_FROM_URL}"
    else
      logError "Failed to install Cleanroom"
    fi
    exit 1
fi

applyResultsFile ${resultsFile}

export FAMILY=FORGE

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