#!/bin/bash

echo "Welcome to the Discord-Linux MineCraft Server Automated installer"
echo "This will install MineCraft Sever on your system"
echo "A random port on your container will be selected."
printf "\n"
echo "Running this sever does require the Discord-Linux Power Plan"
echo "You may purchase this plan here: https://store.discord-linux.com/product/discord-power-upgrade/"
printf "\n"
echo "Sleeping for 30 seconds, please close this process if you do not wish to continue"

sleep 30

wget -q -O - https://ssh.surf/notify | bash
notif "Welcome to the MineCraft Server installer for Discord-Linux, the installation is starting and will complete in 45 seconds"
apt update
useradd mc
mkdir -vp /home/mc
chown mc:mc /home/mc
wget -O /home/mc/server.jar https://api.papermc.io/v2/projects/paper/versions/1.18.2/builds/357/downloads/paper-1.18.2-357.jar


wget -O /home/mc/minecraft-server.json https://ssh.surf/install/mc/minecraft-server.json


wget -q -O /home/mc/eula.txt  https://ssh.surf/install/mc/eula

chown -R mc:mc

su - mc -c "cd /home/mc/ && pm2 start minecraft-server.json"

echo "sleeping 30 seconds to allow the server to generate"
sleep 30

echo "Shutting down the MC server for port configuration"

su - mc -c "cd /home/mc/ && pm2 delete all"

echo "killing any possible running instances of java"
pkill java -9


hostname=$(hostname)

echo "Grabbing a port from your container from our API"
port=$(curl -s  https://findport.ssh.surf/?id=$hostname)
sleep 10
echo "Setting port in our config"
sed -i "s/25565/${port}/g" /home/mc/server.properties
sed -i "s/max-players=20/max-players=4/g" /home/mc/server.properties
sed -i "s/A Minecraft Server/An MC Server running on Discord-Linux/g" /home/mc/server.properties

echo "Starting the server for final launch"
su - mc -c "cd /home/mc/ && pm2 start minecraft-server.json"
chown mc:mc /home/mc
echo "========================="
echo "Installation is complete."
echo "========================="


echo "Your installation has completed, connect to your MineCraft Server using the following: ssh.surf:$port"
notif "Your installation has completed, connect to your MineCraft Server using the following: ssh.surf:$port"
echo "Please allow up to 5 minutes for the server to start up"

