#!/bin/bash

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

if [ "$TYPE" = "CURSEFORGE" ]; then
  worldDest=$FTB_DIR/${LEVEL:-world}
else
  worldDest=/data/${LEVEL:-world}
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"
    if ! get -o /tmp/world.bin "$WORLD"; then
      log "ERROR: failed to download world from $WORLD"
      exit 1
    fi
    WORLD=/tmp/world.bin
  fi

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

    # Stage contents so that the correct subdirectory can be picked off
    mkdir -p /tmp/world-data
    if ! extract "$WORLD" /tmp/world-data; then
      log "ERROR extracting world from $WORLD"
      exit 1
    fi

    baseDirs=$(find /tmp/world-data -name "level.dat" -exec dirname "{}" \;)

    if ! [[ $baseDirs ]]; then
      log "ERROR 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")
        log "WARN multiple levels found, picking: $baseName"
      fi
    elif [[ $count -gt 0 ]]; then
      baseDir="$baseDirs"
    else
      log "ERROR invalid world content"
      exit 1
    fi

    if [ -d "${baseDir}_nether/DIM-1" ]; then
      if [ -d "$baseDir/DIM-1" ]; then
        log "WARN 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
        log "WARN 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
    log "ERROR: 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

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