#!/bin/bash
if screen -list | grep -q "mc-server"; then
    echo "Server läuft bereits!"
    exit 1
fi
RAM=$(cat ram)

cd /home/ubuntu/minecraft-server
> server.log


# Pfad zur Port-Datei
PORT_FILE="/home/ubuntu/minecraft-panel/port"
GEYSER_CONFIG="/home/ubuntu/minecraft-server/plugins/Geyser-Spigot/config.yml"
PLUGINS_DIR="/home/ubuntu/minecraft-server/plugins"

# Lesen des Minecraft-Java-Ports
if [ -f "$PORT_FILE" ]; then
    PORT=$(cat "$PORT_FILE")
else
    PORT=25565
fi

# Bedrock-Port = Java-Port + 1
BEDROCK_PORT=$((PORT + 1))

# Geyser config anpassen, falls Datei existiert
if [ -f "$GEYSER_CONFIG" ]; then
    # Prüfen ob der Eintrag existiert und ersetzen, sonst hinzufügen
    if grep -q "^  port: " "$GEYSER_CONFIG"; then
        sed -i "s/^  port:.*/  port: $BEDROCK_PORT/" "$GEYSER_CONFIG"
    else
        # Einfach am Anfang der Datei nach der Zeile "bedrock:" einfügen
        sed -i "/^bedrock:/a\  port: $BEDROCK_PORT" "$GEYSER_CONFIG"
    fi
fi


# Geyser
GEYSER_URL="https://download.geysermc.org/v2/projects/geyser/versions/latest/builds/latest/downloads/spigot"
GEYSER_JAR="$PLUGINS_DIR/geyser.jar"
GEYSER_HASH_FILE="$PLUGINS_DIR/.geyser_hash"

LATEST_G_HASH=$(wget -qO- "$GEYSER_URL" | sha256sum | cut -d' ' -f1)

if [ ! -f "$GEYSER_HASH_FILE" ] || [ "$(cat $GEYSER_HASH_FILE)" != "$LATEST_G_HASH" ]; then
    echo "Geyser wird aktualisiert..."
    wget -O "$GEYSER_JAR" "$GEYSER_URL"
    echo "$LATEST_G_HASH" > "$GEYSER_HASH_FILE"
else
    echo "Geyser ist aktuell."
fi

# Floodgate
FLOODGATE_URL="https://download.geysermc.org/v2/projects/floodgate/versions/latest/builds/latest/downloads/spigot"
FLOODGATE_JAR="$PLUGINS_DIR/floodgate.jar"
FLOODGATE_HASH_FILE="$PLUGINS_DIR/.floodgate_hash"

LATEST_F_HASH=$(wget -qO- "$FLOODGATE_URL" | sha256sum | cut -d' ' -f1)

if [ ! -f "$FLOODGATE_HASH_FILE" ] || [ "$(cat $FLOODGATE_HASH_FILE)" != "$LATEST_F_HASH" ]; then
    echo "Floodgate wird aktualisiert..."
    wget -O "$FLOODGATE_JAR" "$FLOODGATE_URL"
    echo "$LATEST_F_HASH" > "$FLOODGATE_HASH_FILE"
else
    echo "Floodgate ist aktuell."
fi


echo "$RAM"
screen -dmS mc-server bash -c "java -Xmx$RAM -Xms$RAM -XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 -XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch  -jar server.jar nogui"
