#!/bin/bash

# shellcheck source=start-utils
. "$(dirname "$0")/start-utils"
set -e
isDebugging && set -x

worldDownload=/data/tmp/world.zip
tmpWorldData=/data/tmp/world-data

# support absolute directories
if [[ "${LEVEL:-world}" =~ ^\/.*$ ]]; then
  worldDest=${LEVEL}
else
  if [ "$TYPE" = "CURSEFORGE" ]; then
    worldDest=$FTB_DIR/${LEVEL:-world}
  else
    worldDest=/data/${LEVEL:-world}
  fi
fi

if [[ "$WORLD" ]] && ( isTrue "${FORCE_WORLD_COPY}" || [ ! -d "$worldDest" ] ); then
  if isTrue "${FORCE_WORLD_COPY}"; then
    log "Removing existing world data in $worldDest ${worldDest}_nether ${worldDest}_the_end"
    rm -rf "$worldDest" \
      "${worldDest}_nether" \
      "${worldDest}_the_end"
  fi

  if isURL "$WORLD"; then
    log "Downloading world from $WORLD"
    mkdir -p /data/tmp
    if ! get -o ${worldDownload} "$WORLD"; then
      logError "Failed to download world from $WORLD"
      exit 1
    fi
    WORLD=${worldDownload}
  fi

  if [ -f "$WORLD" ]; then
    log "Extracting world"

    # Stage contents so that the correct subdirectory can be picked off
    mkdir -p ${tmpWorldData}
    if ! extract "$WORLD" ${tmpWorldData}; then
      logError "Extracting world from $WORLD"
      exit 1
    fi

    baseDirs=$(find ${tmpWorldData} -name "level.dat" -exec dirname "{}" \;)

    if ! [[ $baseDirs ]]; then
      logError "World content is not valid since level.dat could not be found"
      exit 2
    fi

    count=$(echo "$baseDirs" | wc -l)
    if [[ $count -gt 1 ]]; then
      baseDirsNoSpigotSuffix=$(echo "$baseDirs" | sed -re 's:(_nether|_the_end)/?$::' | sort -u)
      if [ "$(echo "$baseDirsNoSpigotSuffix" | wc -l)" -eq 1 ]; then
        baseDir="$baseDirsNoSpigotSuffix"
        baseName=$(basename "$baseDir")
        log "Found Spigot naming conventions, taking $baseName as main dimension"
      else
        baseDir="$(echo "$baseDirs" | sed -n ${WORLD_INDEX:-1}p)"
        baseName=$(basename "$baseDir")
        logWarning "Multiple levels found, picking: $baseName"
      fi
    elif [[ $count -gt 0 ]]; then
      baseDir="$baseDirs"
    else
      logError "Invalid world content"
      exit 1
    fi

    if [ -d "${baseDir}_nether/DIM-1" ]; then
      if [ -d "$baseDir/DIM-1" ]; then
        logWarning "Found Nether dimension in both $baseDir and ${baseDir}_nether, picking ${baseDir}_nether"
        rm -r "$baseDir/DIM-1"
      fi
    fi
    if [ -d "${baseDir}_the_end/DIM1" ]; then
      if [ -d "$baseDir/DIM1" ]; then
        logWarning "Found End dimension in both $baseDir and ${baseDir}_the_end, picking ${baseDir}_the_end"
        rm -r "$baseDir/DIM1"
      fi
    fi

    log "Copying world..."
    rsync --remove-source-files --recursive --delete "$baseDir/" "$worldDest"

    if [ "$FAMILY" = "SPIGOT" ]; then
      if [ -d "${baseDir}_nether" ]; then
        log "Copying Spigot Nether..."
        rsync --remove-source-files --recursive --delete "${baseDir}_nether/" "${worldDest}_nether"
      elif [ -d "$worldDest/DIM-1" ]; then
        log "Moving Nether to Spigot location..."
        mkdir -p "${worldDest}_nether"
        mv -f "$worldDest/DIM-1" "${worldDest}_nether/"
      fi
      if [ -d "${baseDir}_the_end" ]; then
        log "Copying Spigot End..."
        rsync --remove-source-files --recursive --delete "${baseDir}_the_end/" "${worldDest}_the_end"
      elif [ -d "$worldDest/DIM1" ]; then
        log "Moving End to Spigot location..."
        mkdir -p "${worldDest}_the_end"
        mv -f "$worldDest/DIM1" "${worldDest}_the_end/"
      fi
    else
      if [ -d "${baseDir}_nether/DIM-1" ]; then
        log "Copying Spigot Nether to vanilla location..."
        rsync --remove-source-files --recursive --delete "${baseDir}_nether/DIM-1" "${worldDest}/"
      fi
      if [ -d "${baseDir}_the_end/DIM1" ]; then
        log "Copying Spigot End to vanilla location..."
        rsync --remove-source-files --recursive --delete "${baseDir}_the_end/DIM1" "${worldDest}/"
      fi
    fi
  elif [ -d "$WORLD" ]; then
    log "Cloning world directory from $WORLD ..."
    rsync --recursive --delete "${WORLD%/}"/ "$worldDest"
  else
    logError "World file/directory $WORLD is missing"
    exit 1
  fi

  if [ "$FAMILY" = "SPIGOT" ]; then
    # Reorganise if a Spigot server
    log "Moving End and Nether maps to Spigot location"
    [ -d "$worldDest/DIM1" ] && mv -f "$worldDest/DIM1" "${worldDest}_the_end"
    [ -d "$worldDest/DIM-1" ] && mv -f "$worldDest/DIM-1" "${worldDest}_nether"
  fi
fi

[[ -f ${worldDownload} ]] && rm ${worldDownload}
[[ -d ${tmpWorldData} ]] && rm -rf ${tmpWorldData}

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