#!/bin/bash

# shellcheck source=start-utils
. "${SCRIPTS:-/}start-utils"

: "${SERVER_PROPERTIES:=/data/server.properties}"
: "${OVERRIDE_SERVER_PROPERTIES:=true}"
: "${SKIP_SERVER_PROPERTIES:=false}"
: "${ENABLE_WHITELIST:=}"

function customizeServerProps {
  local firstSetup=$1
  # Whitelist processing
  if [ -n "$WHITELIST" ] || [ -n "$WHITELIST_FILE" ] || isTrue "${ENABLE_WHITELIST}"; then
    log "Enabling whitelist functionality"
    WHITELIST_PROP=true
    ENFORCE_WHITELIST=true
    export WHITELIST_PROP ENFORCE_WHITELIST
  elif isTrue "$firstSetup" || isFalse "${ENABLE_WHITELIST}"; then
    log "Disabling whitelist functionality"
    WHITELIST_PROP=false
    export WHITELIST_PROP
  fi

  # normalize MOTD
  if [[ ${TYPE^^} = LIMBO ]]; then
    if [[ $MOTD ]] && ! [[ $MOTD =~ ^{ ]]; then
      # shellcheck disable=SC2089
      MOTD="{\"text\":\"${MOTD}\"}"
    fi
  fi

  if [[ -v MODE ]]; then
    log "Setting mode"
    case ${MODE,,} in
      su*|0)
        if versionLessThan 1.13; then
          MODE=0
        else
          MODE=survival
        fi
        ;;
      c*|1)
        if versionLessThan 1.13; then
          MODE=1
        else
          MODE=creative
        fi
        ;;
      a*|2)
        if versionLessThan 1.13; then
          MODE=2
        else
          MODE=adventure
        fi
        ;;
      sp*|3)
        if versionLessThan 1.13; then
          MODE=3
        else
          MODE=spectator
        fi
        ;;
      *)
        log "ERROR: Invalid game mode: $MODE"
        exit 1
        ;;
    esac
  fi

  if [[ -v DIFFICULTY ]]; then
    case ${DIFFICULTY,,} in
      peaceful|0)
        if versionLessThan 1.13; then
          DIFFICULTY=0
        else
          DIFFICULTY=peaceful
        fi
        ;;
      easy|1)
        if versionLessThan 1.13; then
          DIFFICULTY=1
        else
          DIFFICULTY=easy
        fi
        ;;
      normal|2)
        if versionLessThan 1.13; then
          DIFFICULTY=2
        else
          DIFFICULTY=normal
        fi
        ;;
      hard|3)
        if versionLessThan 1.13; then
          DIFFICULTY=3
        else
          DIFFICULTY=hard
        fi
        ;;
      *)
        log "DIFFICULTY must be peaceful, easy, normal, or hard."
        exit 1
        ;;
    esac
  fi

  if [[ -v LEVEL_TYPE ]]; then
    LEVEL_TYPE="${LEVEL_TYPE^^}"
  fi

  setPropertiesArgs=(
    --definitions "/image/property-definitions.json"
  )
  if [[ -v CUSTOM_SERVER_PROPERTIES ]]; then
    setPropertiesArgs+=(--custom-properties "$CUSTOM_SERVER_PROPERTIES")
  fi
  if [[ -v SERVER_PROPERTIES_ESCAPE_UNICODE ]]; then
    if isTrue "$SERVER_PROPERTIES_ESCAPE_UNICODE"; then
      setPropertiesArgs+=(--escape-unicode)
    fi
  elif versionLessThan '1.20'; then
    setPropertiesArgs+=(--escape-unicode)
  fi

  handleDebugMode
  if ! mc-image-helper set-properties "${setPropertiesArgs[@]}" "$SERVER_PROPERTIES"; then
    log "ERROR: failed to update server.properties"
    exit 1
  fi

}

# Deploy server.properties file
if [[ ${TYPE} == "CURSEFORGE" ]]; then
  export SERVER_PROPERTIES="${FTB_DIR}/server.properties"
  log "detected FTB, changing properties path to ${SERVER_PROPERTIES}"
fi

if ! isTrue "${SKIP_SERVER_PROPERTIES}"; then
  if [ ! -e "$SERVER_PROPERTIES" ]; then
    log "Creating server properties in ${SERVER_PROPERTIES}"

    # If not provided, generate a reasonable default message-of-the-day,
    # which shows up in the server listing in the client
    if ! [ -v MOTD ]; then
      # snapshot is the odd case where we have to look at version to identify that label
      if [[ ${DECLARED_TYPE} == "VANILLA" && ${VERSION} == "SNAPSHOT" ]]; then
        label=SNAPSHOT
      else
        label=${DECLARED_TYPE}
      fi

      # Convert label to title-case
      label=${label,,}
      label=${label^}
      MOTD="A ${label} Minecraft Server powered by Docker"
    fi

    customizeServerProps true
  elif isTrue "${OVERRIDE_SERVER_PROPERTIES}"; then
    customizeServerProps false
  else
    log "server.properties already created and managed manually"
  fi
else
  log "Skipping setup of server.properties"
fi

if isTrue "${ENABLE_AUTOPAUSE}"; then
  if [ -f "$SERVER_PROPERTIES" ]; then
    current_max_tick=$( grep 'max-tick-time' "$SERVER_PROPERTIES" | sed -r 's/( )+//g' | awk -F= '{print $2}' )
    if (( current_max_tick > 0 && current_max_tick < 86400000 )); then
      log "Warning: The server.properties for the server doesn't have the Server Watchdog (effectively) disabled."
      log "         Autopause functionality resuming the process might trigger the Watchdog and restart the server completely."
      log "         Set the MAX_TICK_TIME env variable (or max-tick-time property) to a high value (or disable the Watchdog with value -1 for versions 1.8.1+)."
    fi
  fi
fi

if isTrue "${DUMP_SERVER_PROPERTIES:-false}"; then
  log "DEBUG Dumping server.properties"
  cat "${SERVER_PROPERTIES}"
fi

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