#!/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
mkdir start-temp
cd start-temp
wget -O geyser.jar https://download.geysermc.org/v2/projects/geyser/versions/latest/builds/latest/downloads/spigot
geyser_new_sha=$(sha256sum geyser.jar | awk '{print $1}')
geyser_old_sha=$(sha256sum /home/ubuntu/minecraft-server/plugins/geyser.jar | awk '{print $1}')

if ! [ $geyser_new_sha == $geyser_old_sha ]; then
    echo "Eine neue Version von Geyser ist verfügbar"
    rm /home/ubuntu/minecraft-server/plugins/geyser.jar
    cp geyser.jar /home/ubuntu/minecraft-server/plugins
    cd ..
    rm -rf start-temp
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"
