#!/bin/bash
PORT_FILE='port'
GEYSER_CONFIG='../minecraft-server/plugins/Geyser-Spigot/config.yml'
PLUGINS_DIR='../minecraft-server/plugins'

base_directory=$(cat base_directory)
if [ -f '$PORT_FILE' ]; then
    PORT=$(cat '$PORT_FILE')
else
    PORT=25565
fi

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

if [[ -f "$PLUGINS_DIR" ]]; then
    echo "Pluginsordner existiert"
    # Geyser update
    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 $base_directory/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 $base_directory/minecraft-server/plugins/geyser.jar
        cp geyser.jar $base_directory/minecraft-server/plugins
        cd ..
        rm -rf start-temp
    else 
        echo 'Geyser ist aktuell!'
        cd ..
        rm -rf start-temp
    fi

    #Floodgate update
    mkdir start-temp
    cd start-temp
    wget -O floodgate.jar https://download.geysermc.org/v2/projects/floodgate/versions/latest/builds/latest/downloads/spigot
    floodate_new_sha=$(sha256sum floodgate.jar | awk '{print $1}')
    floodgate_old_sha=$(sha256sum ../../minecraft-server/plugins/floodgate.jar | awk '{print $1}')

    if ! [ $floodate_new_sha == $floodgate_old_sha ]; then  
        echo 'Eine neue Version von Floodgate ist verfügbar'
        rm ../../minecraft-server/plugins/floodgate.jar
        cp floodgate.jar ../../minecraft-server/plugins
        cd ..
        rm -rf start-temp
    else
        echo 'floodgate ist aktuell!'
        cd ..
        rm -rf start-temp
    fi
fi





RAM=$(cat ram)
cd ../minecraft-server

if ! [[ -f "server.properties" ]]; then
    echo "server-port=$PORT" >> "server.properties"
fi



#Execute Command
bash execute-start.sh $RAM
