#!/bin/bash

: "${FTB_FORCE_REINSTALL:=false}"

ftbInstallMarker=".ftb-installed"

# shellcheck source=start-utils
. "${SCRIPTS:-/}start-utils"
isDebugging && set -x
set -e

if [[ $(getDistro) = alpine ]]; then
  log "ERROR: the FTBA installer is not supported on Alpine. Use the java8-multiarch image tag instead."
  exit 1
fi

if ! [[ -v FTB_MODPACK_ID ]]; then
  log "ERROR FTB_MODPACK_ID is required with TYPE=FTB"
  exit 1
fi

if ! [[ ${FTB_MODPACK_ID} =~ [0-9]+ ]]; then
  log "ERROR FTB_MODPACK_ID needs to be numeric"
  exit 1
fi

if [[ ! $FTB_MODPACK_VERSION_ID ]]; then
  if ! FTB_MODPACK_VERSION_ID=$(curl -fsSL https://api.modpacks.ch/public/modpack/${FTB_MODPACK_ID} | jq -r '.versions | sort_by(.updated)[-1].id'); then
    log "ERROR unable to resolve latest modpack version ID for modpack ${FTB_MODPACK_ID}"
    exit 1
  fi
elif ! [[ ${FTB_MODPACK_VERSION_ID} =~ [0-9]+ ]]; then
  log "ERROR FTB_MODPACK_VERSION_ID needs to be numeric"
  exit 1
fi

if isTrue "$FTB_FORCE_REINSTALL" || ! [ -f "${ftbInstallMarker}" ] || [ "$(cat "${ftbInstallMarker}")" != "${FTB_MODPACK_ID}=${FTB_MODPACK_VERSION_ID}" ]; then
  ftbInstaller=/data/ftb-installer
  if ! [[ -f "${ftbInstaller}" ]]; then
    log "Downloading FTB installer"
    if [ "$(uname -m)" == "aarch64" ]; then
      log "Downloading ARM installer"
      curl -fsSL https://api.modpacks.ch/public/modpack/1/1/server/arm/linux -o "${ftbInstaller}"
    else
      log "Downloading x86 installer"
      curl -fsSL https://api.modpacks.ch/public/modpack/1/1/server/linux -o "${ftbInstaller}"
    fi
    chmod +x "${ftbInstaller}"
  fi

  log "Installing modpack ID ${FTB_MODPACK_ID}, version ID ${FTB_MODPACK_VERSION_ID}"
  log "This could take a while..."
  ${ftbInstaller} "${FTB_MODPACK_ID}" "${FTB_MODPACK_VERSION_ID}" --noscript --auto > ftb-installer.log
  rm -f forge*installer.jar

  echo "${FTB_MODPACK_ID}=${FTB_MODPACK_VERSION_ID}" > ${ftbInstallMarker}

  writeEula

  # some modpacks result in --w----r-- permissions
  chmod a+r version.json
else
  log "FTB modpack ID ${FTB_MODPACK_ID}, version ID ${FTB_MODPACK_VERSION_ID} is ready to go"
fi

forgeVersion=$(jq -r '.targets|unique[] | select(.name == "forge") | .version' version.json)
fabricVersion=$(jq -r '.targets|unique[] | select(.name == "fabric") | .version' version.json)
mcVersion=$(jq -r '.targets|unique[] | select(.name == "minecraft") | .version' version.json)
VERSION="$mcVersion"
export VERSION

variants=(
  "forge-${mcVersion}-${forgeVersion}.jar"
  "forge-${mcVersion}-${forgeVersion}-universal.jar"
  "forge-${mcVersion}-${forgeVersion}-${mcVersion}-universal.jar"
  "fabric-${mcVersion}-${fabricVersion}-server-launch.jar"
  run.sh
)
for f in "${variants[@]}"; do
  if [ -f $f ]; then
    export SERVER=$f
    break
  fi
done
if ! [ -v SERVER ]; then
  log "ERROR unable to locate the installed FTB server jar"
  log "      Tried looking for ${variants[*]}"
  exit 2
fi

export FAMILY=FORGE

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