#!/bin/bash

# https://github.com/itzg/dockerfiles/blob/master/minecraft-server/start.sh

set -e
sed -i "/^minecraft/s/:1000:1000:/:${UID}:${GID}:/g" /etc/passwd
sed -i "/^minecraft/s/:1000:/:${GID}:/g" /etc/group

cd /home/minecraft

if [ ! -e eula.txt ]; then
  echo "# Generated via Docker at $(date)" > eula.txt
  echo "eula=TRUE" >> eula.txt
  chown ${UID}:${GID} eula.txt
fi


if [ ! -e server.properties ]; then
  echo "Missing server.properties"
  exit 99
fi

# create ops.txt file with the names

# There whitelist code https://github.com/itzg/dockerfiles/blob/master/minecraft-server/start-minecraft.sh#L540
# but it doesn't work.  See https://www.beastnode.com/portal/knowledgebase/6/Setting-Up-a-Whitelist-or-Make-Your-Server-Private.html
# on using /whitelist add username (to actually setup and use the whitelist.json file)   :P

if [ ! -e banned-players.json ]; then
  echo '[]' > banned-players.json
  chown ${UID}:${GID} banned-players.json
fi

if [ ! -e banned-ips.json ]; then
  echo '[]' > banned-ips.json
  chown ${UID}:${GID} banned-ips.json
fi

EXTRA_ARGS=""

# Optional disable console
if [[ ${CONSOLE} = false || ${CONSOLE} = FALSE ]]; then
  EXTRA_ARGS+="--noconsole"
fi

# Optional disable GUI for headless servers
if [[ ${GUI} = false || ${GUI} = FALSE ]]; then
  EXTRA_ARGS="${EXTRA_ARGS} nogui"
fi

# put these prior JVM_OPTS at the end to give any memory settings there higher precedence
echo "Setting initial memory to ${INIT_MEMORY:-${MEMORY}} and max to ${MAX_MEMORY:-${MEMORY}}"
JVM_OPTS="-Xms${INIT_MEMORY:-${MEMORY}} -Xmx${MAX_MEMORY:-${MEMORY}} ${JVM_OPTS}"

echo "Switching to user 'minecraft' and launching $SERVER"

# start in the backround

su-exec minecraft java $JVM_XX_OPTS $JVM_OPTS $STARTUP -jar $SERVER "$@" $EXTRA_ARGS &
MC_PID=$!
echo "Minecraft running pid $MC_PID ..."

RCON="rcon-cli --port 25575 --password mindcraft"

save_shutdown() {
  echo "Received TERM..."
  echo "Warning users"
  $RCON say "Saving and Shutting down Minecraft now"
  sleep 1
  echo "Saving..."
  $RCON save-all
  sleep 1
  echo "Stop..."
  $RCON stop
  wait $MC_PID
}

# Ok, trap TERM
trap save_shutdown TERM INT
echo "Waiting for Minecraft ($MC_PID)..."
wait $MC_PID

echo "Minecraft is shutdown."

