#!/bin/bash
echo -n "$(tput setaf 5)"
echo -e "Minecraft Ubuntu Server Builder/install v1.0"
echo -e

echo -n "$(tput setaf 7)"
echo -e "Installation java:"
if ! [ -x "$(command -v java)" ]
then
sudo apt-get update
sudo apt-get install curl wget git -y
if ! [ -f openjdk-18_linux-x64_bin.tar.gz ]
then
curl -O https://download.java.net/java/GA/jdk18/43f95e8614114aeaa8e8a5fcf20a682d/36/GPL/openjdk-18_linux-x64_bin.tar.gz
fi
cat <<'EOF'>> openjdk-18_linux-x64_bin.tar.gz.md5
f3fc42bd35c3f5e9aff967c9862a153a  openjdk-18_linux-x64_bin.tar.gz
EOF
if md5sum -c openjdk-18_linux-x64_bin.tar.gz.md5
then
tar xf openjdk-18_linux-x64_bin.tar.gz
rm openjdk-18_linux-x64_bin.tar.gz.md5
else
echo "erreur"
fi
if [ -d /opt/jdk-18 ]
then
sudo rm -r /opt/jdk-18/
fi
sudo mv jdk-18 /opt/
sudo rm openjdk-18_linux-x64_bin.tar.gz
if  [ -f /etc/profile.d/jdk18.sh ]
then
sudo rm /etc/profile.d/jdk18.sh
fi
sudo tee /etc/profile.d/jdk18.sh <<EOF
export JAVA_HOME=/opt/jdk-18
export PATH=\$PATH:\$JAVA_HOME/bin
EOF
source /etc/profile.d/jdk18.sh
fi
version=$(java -version 2>&1 | head -1 | cut -d'"' -f2 | sed '/^1\./s///' | cut -d'.' -f1)
if [ $version -ge 18 ]
then
echo -e "\n$(tput setaf 5)Java version >= 18 ... ok$(tput setaf 7)\n"
else
echo "error"
exit 1
fi
echo "Done."

echo -e "Download mcrcon:"
cd /home/wareck/
git clone https://github.com/Tiiffi/mcrcon.git
cd /home/wareck/mcrcon
make
sudo make install
cd ..
rm -r -f /home/wareck/mcrcon
echo -e "Done"

echo -e "Download Minecraft server structure:"
cd /home/wareck/
wget -c http://folivier.homelinux.org/cube/pack/minecraft.tar.xz
tar xvfJ minecraft.tar.xz
rm minecraft.tar.xz
cd minecraft

echo -e ""
echo -e "Chargement BuildTools:"
if ! [ -d build ]; then mkdir build ;fi
cd build
wget -c https://hub.spigotmc.org/jenkins/job/BuildTools/lastSuccessfulBuild/artifact/target/BuildTools.jar
echo -e "Done."
echo -e ""
echo -e "Compilation Spigot:"
java -jar BuildTools.jar

git clone https://github.com/Tiiffi/mcrcon.git
cd mcrcon
make
sudo make install
cd ..
sudo rm mcrcon
rsync --append --progress --recursive * /home/wareck/minecraft/
echo -e "Done"
cd ..


echo -e "\nGeneration fichier service:"
if [ -f minecraft.service ]
then
rm minecraft.service
fi
cat <<'EOF'>> minecraft.service
#!/bin/sh -e
### BEGIN INIT INFO
# Provides:          minecraft
# Required-Start:    networking
# Default-Start:     3 4 5
# Default-Stop:      0 6
### END INIT INFO
cd /home/wareck/minecraft/
su wareck -c "screen -dmS minecraft /opt/jdk-18/bin/java -jar -Xmx1024M -Xms1024M spigot-1.18.2.jar nogui"
exit 0
EOF
chmod +x minecraft.service
sudo cp minecraft.service /etc/init.d/
sudo sudo update-rc.d minecraft.service defaults

echo -e "Done"
