diff --git a/README.md b/README.md index 3e7adf8..e5996c2 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,35 @@ -MinecraftServer -=============== +# MinecraftServer + Scripts for a Minecraft Server on Linux Debian using screen. -This tutorial contains important steps if you would like to host a minecraft server from the command line. +This tutorial contains important steps if you would like to host a minecraft server from the command line. + ## software + In order for the Server to run we will need to install some packages: (please note: some of them could be installed already)
This command installs all packages you will need to run your server. + ``` sudo apt install openjdk-17-jre-headless iputils-ping net-tools mailutils coreutils dnsutils sendmail screen grep nano wget less cron man sed pv ``` + ## setup + Then, you can download and execute the setup script.
-This command downloads, makes exectable and executes the setup script. +This command downloads, makes exectable and executes the setup script. + ``` wget -O setup.sh https://raw.githubusercontent.com/Simylein/MinecraftServer/main/setup.sh && chmod +x setup.sh && ./setup.sh ``` -The Script will ask you some Questions. Please answer them in order for the Server to work. If you do not know what you like right now you can edit all answers later in the server.* files and going with the prefilled answer works for most people. Now you got yourself a server directory. It is called ${servername} (it's the name you have chosen for your server) and inside ${servername} a directory is called backups. Like you can imagine ${servername} holds your live server and backups stores your backups. + +The Script will ask you some Questions. Please answer them in order for the Server to work. If you do not know what you like right now you can edit all answers later in the server.\* files and going with the prefilled answer works for most people. Now you got yourself a server directory. It is called ${servername} (it's the name you have chosen for your server) and inside ${servername} a directory is called backups. Like you can imagine ${servername} holds your live server and backups stores your backups. + ## serverstart + Start your Server for the first time: `./start.sh` ## screen + Screen is an amzing comand line tool that creates a "virtual" terminal inside your terminal. You can view all your active screens by typing: `screen -list` @@ -30,7 +40,9 @@ If you would like to scroll inside a screen session press Ctrl+A and Esc (enter For returning back to normal press Esc. To exit the screen terminal press Ctrl+A and Ctrl+D + ## server commands + Your minecraft server can understand certain commands.
I will explain some of them to you. @@ -44,19 +56,24 @@ I will explain some of them to you. `tp ${playername} ${playername}` teleporting a player to another player. Important: If you do these commands ingame you will need to put a `/` before each command.
-In the screen terminal you don't need a `/` before your command. +In the screen terminal you don't need a `/` before your command. + ## server.settings + This is your file that holds the variables you have chosen with the setup script.
If you know what your are doing feel free to edit it to suit your needs. + ``` nano server.settings ``` + It looks like this: (there will be alot of variables after setup.sh) + ``` #!/bin/bash # minecraft server settings -# This file stores all the variables for the server. +# This file stores all the variables for the server. # If you know what you are doing, feel free to tinker with them ;^) # command line colours @@ -71,44 +88,53 @@ white="$(tput setaf 7)" nocolor="$(tput sgr0)" ... ``` + ## server.properties -If you would like to costumize your server further have a look at your server.properties file. + +If you would like to costumize your server further have a look at your server.properties file. + ``` nano server.properties ``` + Important settings are: -`max-players=` (limuts the maximumg amount of players on the server at the same time)
- [Warning large numbers may impact performance]
-`difficulty=` (defines ingame difficulty) [peaceful, easy, normal, hard]
-`view-distance=` (defines number of ingame chnuks to be rendered)
- [Warning large numbers may impact performance]
-`white-list=` (turns on the whitelist) [I would strongely recomment to set this to true]
-`motd=` (this will be displayed in the menu below your server - chose what you like)
-`server-port=` (default by 25565. Only importent if you are dealing with multiple server)
- [if you run multiple servers each server wants to have its own port]
-`gamemode=` (default survival. Defines your game mode. For creative server replace with creative)
- [survival/creative/adventure/spectator]
-`spawn-protection=` (the number of block at the worldspawn only operators can touch)
-`pvp=` (ability for player to do damage to oneanother) [true/false]
+`max-players=` (limuts the maximumg amount of players on the server at the same time)
+[Warning large numbers may impact performance]
+`difficulty=` (defines ingame difficulty) [peaceful, easy, normal, hard]
+`view-distance=` (defines number of ingame chnuks to be rendered)
+[Warning large numbers may impact performance]
+`white-list=` (turns on the whitelist) [I would strongely recomment to set this to true]
+`motd=` (this will be displayed in the menu below your server - chose what you like)
+`server-port=` (default by 25565. Only importent if you are dealing with multiple server)
+[if you run multiple servers each server wants to have its own port]
+`gamemode=` (default survival. Defines your game mode. For creative server replace with creative)
+[survival/creative/adventure/spectator]
+`spawn-protection=` (the number of block at the worldspawn only operators can touch)
+`pvp=` (ability for player to do damage to oneanother) [true/false]
`enable-command-block=` (enables command blocks to tinker with) [true/false]
## scripts + There are lots of script in your ${serverdirectory}. Normally, the executable ones are green and can be executed with: ``` ./${scriptname}.sh ${arguments} ``` -Example: `./start.sh -v` +Example: `./start.sh -verbose` +Example: `./start.sh -now` -Arguments: `-i --immediately -q --quiet -v --verbose` +Arguments: `-f --force, -n --now -q --quiet -v --verbose` ## crontab + If you would like to automate some of those task on your server you can create a crontab. + ``` crontab -e ``` + A new file will open (If you got one already the existing one will open)
Side note: the setup script will already put these lines in your crontab if you chose to do so.
In this file, you can automate things as follows:
@@ -120,22 +146,29 @@ Forth star: Month [0 - 12]
Fifth star: Day of Week [0 - 6] Generic Example: (In order to work, please replace the variables with your own ones) + ``` # minecraft ${servername} your description of command here * * * * * cd ${serverdirectory} && ${serverdirectory}/NameOfScript.sh ``` + Close and save your crontab. (Press Ctrl X and Y) + ## logfiles + Your server will write two growing logfiles (located in your ${serverdirectory})
screen.log and backup.log
-screen.log contains everything that get's written inside your screen terminal while backup.log logs all action of the backup script. +screen.log contains everything that get's written inside your screen terminal while backup.log logs all action of the backup script. to view them: + ``` less screen.log less backup.log ``` + ## ending + I hope you learned something and that those scripts I provide may help you and your minecraft server experience.
Have fun and enjoy the Game ;^) diff --git a/backup.sh b/backup.sh index b9225a5..8d07dfc 100644 --- a/backup.sh +++ b/backup.sh @@ -1,429 +1,158 @@ #!/bin/bash # minecraft server backup script -# this script is meant to be executed every hour by crontab -# 0 * * * * cd ${serverdirectory} ./backup.sh --quiet - -# if you want you can change the time of day on which -# daily backups are made as an example in server.settings, but please beware: - # for the sake of integrity of your backups, # I would strongly recommend not to mess with this file. # if you really know what you are doing feel free to go ahead ;^) -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi +# read server files +source server.settings +source server.functions -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi +# parse backup category +ParseCategory "$@" -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi +# shift args +shift -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi +# parse arguments +ParseArgs "$@" +ArgHelp -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi - -# parsing script arguments -ParseScriptArguments "$@" - -# test if all categories for backups exists if not create them -CheckBackupDirectoryIntegrity +# safety checks +RootSafety +ScriptSafety +# debug +Debug "executing $0 script" -# check if hourly backups are anabled -if [ ${dohourly} = true ]; then +# change to server directory +ChangeServerDirectory - # write date and execute into logfiles - echo "action: ${date} executing backup-hourly script" >> ${screenlog} - echo "action: ${date} executing backup-hourly script" >> ${backuplog} - CheckDebug "executing backup-hourly script" - - # start milliseconds timer - before=$(date +%s%3N) +# check if server is running +CheckScreen - # checks for the existence of a screen terminal - if ! screen -list | grep -q "\.${servername}"; then - echo "${yellow}server is not currently running!${nocolor}" - echo "info: server is not currently running!" >> ${screenlog} - echo "info: server is not currently running!" >> ${backuplog} - echo "" >> ${backuplog} - exit 1 - fi +# test all categories +BackupDirectoryIntegrity - # check if world is bigger than diskspace - if (( (${absoluteworldsize} + ${diskspacepadding}) > ${absolutediskspace} )); then - # ingame, terminal and logfile error output - PrintToScreenNotEnoughtDiskSpace "${newhourly}" "${oldhourly}" - PrintToLogNotEnoughDiskSpace "hourly" - PrintToTerminalNotEnoughDiskSpace "hourly" - CheckDebug "backup script reports not enough disk-space while performing backup-hourly" +# main backup function +function RunBackup { + Debug "executing backup-${1} script" + # check if disk space is too low + if (((${worldSizeBytes} + ${diskSpaceError}) > ${diskSpaceBytes})); then + OutputDiskSpaceError "${1}" "${2}" "${3}" exit 1 fi - - # check if disk space is getting low - if (( (${absoluteworldsize} + ${diskspacewarning}) > ${absolutediskspace} )); then - PrintToScreenDiskSpaceWarning "${newhourly}" "${oldhourly}" - PrintToLogDiskSpaceWarning - PrintToTerminalDiskSpaceWarning - CheckDebug "backup script reports low disk-space while performing backup-hourly" - fi - - # check if there is no backup from the current hour - if ! [[ -s "${backupdirectory}/hourly/${servername}-${newhourly}.tar.gz" ]]; then - if [[ -s "world.tar.gz" ]]; then - rm world.tar.gz - fi - PrintToScreen "save-off" - tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/hourly/${servername}-${newhourly}.tar.gz - PrintToScreen "save-on" - else - PrintToScreenBackupAlreadyExists "${newhourly}" "${oldhourly}" - PrintToLogBackupAlreadyExists "hourly" - PrintToTerminalBackupAlreadyExists "hourly" - CheckDebug "backup script reports backup already exists while performing backup-hourly" - exit 1 - fi - - # check if there is a new backup - if [[ -s "${backupdirectory}/hourly/${servername}-${newhourly}.tar.gz" ]]; then - # check if an old backup exists an remove it - if [[ -s "${backupdirectory}/hourly/${servername}-${oldhourly}.tar.gz" ]]; then - rm ${backupdirectory}/hourly/${servername}-${oldhourly}.tar.gz - fi - # stop milliseconds timer - after=$(date +%s%3N) - # calculate time spent on backup process - timespent=$((${after}-${before})) - # get compressed backup size - compressedbackup=$(du -sh ${backupdirectory}/hourly/${servername}-${newhourly}.tar.gz | cut -f1) - # read server.settings file again - . ./server.settings - # ingame and logfile success output - PrintToScreenBackupSuccess "${newhourly}" "${oldhourly}" - PrintToLogBackupSuccess "${newhourly}" "${oldhourly}" - PrintToTerminalBackupSuccess "${newhourly}" "${oldhourly}" - CheckDebug "backup script reports backup success while performing backup-hourly" - else - # ingame and logfile error output - PrintToScreenBackupError "${newhourly}" "${oldhourly}" - PrintToLogBackupError - PrintToTerminalBackupError - CheckDebug "backup script reports backup error while performing backup-hourly" + # check is getting low + if (((${worldSizeBytes} + ${diskSpaceWarning}) > ${diskSpaceBytes})); then + OutputDiskSpaceWarning "${1}" fi - -else - # write to logfiles that it's disabled - CheckDebug "info: backup-hourly is disabled" - echo "info: backup-hourly is disabled" >> ${backuplog} - echo "" >> ${backuplog} -fi - - -# check if it is the right time -if [ ${hours} -eq ${dailybackuptime} ]; then - - # write date and execute into logfiles - echo "action: ${date} executing backup-daily script" >> ${screenlog} - echo "action: ${date} executing backup-daily script" >> ${backuplog} - CheckDebug "executing backup-daily script" - - # check if daily backups are anabled - if [ ${dodaily} = true ]; then - - # start milliseconds timer + # check if backup already exists + if ! [[ -s "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" ]]; then + # disable auto save + Screen "save-off" + sleep 1s before=$(date +%s%3N) - - # checks for the existence of a screen terminal - if ! screen -list | grep -q "\.${servername}"; then - echo "${yellow}server is not currently running!${nocolor}" - echo "info: server is not currently running!" >> ${screenlog} - echo "info: server is not currently running!" >> ${backuplog} - echo "" >> ${backuplog} + # copy world + nice -n 19 cp -r "world" "tmp-${1}" + if [ $? != 0 ]; then + OutputBackupCopyError "${1}" "${2}" "${3}" + rm -r "tmp-${1}" exit 1 fi - - # check if world is bigger than diskspace - if (( (${absoluteworldsize} + ${diskspacepadding}) > ${absolutediskspace} )); then - # ingame, terminal and logfile error output - PrintToScreenNotEnoughtDiskSpace "${newdaily}" "${olddaily}" - PrintToLogNotEnoughDiskSpace "daily" - PrintToTerminalNotEnoughDiskSpace "daily" - CheckDebug "backup script reports not enough disk-space while performing backup-daily" + # compress world + nice -n 19 tar -czf "world-${1}.tar.gz" "tmp-${1}" + if [ $? != 0 ]; then + OutputBackupTarError "${1}" "${2}" "${3}" + rm -r "world-${1}.tar.gz" "tmp-${1}" exit 1 fi - - # check if disk space is getting low - if (( (${absoluteworldsize} + ${diskspacewarning}) > ${absolutediskspace} )); then - PrintToScreenDiskSpaceWarning "${newdaily}" "${olddaily}" - PrintToLogDiskSpaceWarning - PrintToTerminalDiskSpaceWarning - CheckDebug "backup script reports low disk-space while performing backup-daily" - fi - - # check if there is no backup from the current day - if ! [[ -s "${backupdirectory}/daily/${servername}-${newdaily}.tar.gz" ]]; then - if [[ -s "world.tar.gz" ]]; then - rm world.tar.gz - fi - PrintToScreen "save-off" - tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/daily/${servername}-${newdaily}.tar.gz - PrintToScreen "save-on" - else - PrintToScreenBackupAlreadyExists "${newdaily}" "${olddaily}" - PrintToLogBackupAlreadyExists "daily" - PrintToTerminalBackupAlreadyExists "daily" - CheckDebug "backup script reports backup already exists while performing backup-daily" + # mv backup and remove tmp + nice -n 19 mv "${serverDirectory}/world-${1}.tar.gz" "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" + nice -n 19 rm -r "tmp-${1}" + # enable auto save + after=$(date +%s%3N) + Screen "save-on" + sleep 1s + else + OutputBackupAlreadyExists "${1}" "${2}" "${3}" + exit 1 + fi + if [[ -s "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" ]]; then + # remove old backup if it exists + if [[ -s "${backupDirectory}/${1}/${serverName}-${3}.tar.gz" ]]; then + nice -n 19 rm "${backupDirectory}/${1}/${serverName}-${3}.tar.gz" + fi + # calculate time spent and compression + timeSpent=$((${after} - ${before})) + compressedBackupSize=$(du -sh ${backupDirectory}/${1}/${serverName}-${2}.tar.gz | cut -f1) + compressedBackupSizeBytes=$(du -s ${backupDirectory}/${1}/${serverName}-${2}.tar.gz | cut -f1) + # TODO: fix this buggy mess + # check if backup size is to small for a real backup + if ((${compressedBackupSizeBytes} < (${worldSizeBytes} / (100 * ${backupSizeError})))); then + OutputBackupSizeError "${1}" "${2}" "${3}" exit 1 fi - - # check if there is a new backup - if [[ -s "${backupdirectory}/daily/${servername}-${newdaily}.tar.gz" ]]; then - # check if an old backup exists an remove it - if [[ -s "${backupdirectory}/daily/${servername}-${olddaily}.tar.gz" ]]; then - rm ${backupdirectory}/daily/${servername}-${olddaily}.tar.gz - fi - # stop milliseconds timer - after=$(date +%s%3N) - # calculate time spent on backup process - timespent=$((${after}-${before})) - # get compressed backup size - compressedbackup=$(du -sh ${backupdirectory}/daily/${servername}-${newdaily}.tar.gz | cut -f1) - # read server.settings file again - . ./server.settings - # ingame and logfile success output - PrintToScreenBackupSuccess "${newdaily}" "${olddaily}" - PrintToLogBackupSuccess "${newdaily}" "${olddaily}" - PrintToTerminalBackupSuccess "${newdaily}" "${olddaily}" - CheckDebug "backup script reports backup success while performing backup-daily" - else - # ingame and logfile error output - PrintToScreenBackupError "${newdaily}" "${olddaily}" - PrintToLogBackupError - PrintToTerminalBackupError - CheckDebug "backup script reports backup error while performing backup-daily" + # TODO: fix this buggy mess + # check if backup size is suspiciously small + if ((${compressedBackupSizeBytes} < (${worldSizeBytes} / (100 * ${backupSizeWarning})))); then + OutputBackupSizeWarning "${1}" "${2}" "${3}" fi - + # read settings and output success + source server.settings + OutputBackupSuccess "${1}" "${2}" "${3}" + else + OutputBackupGenericError "${1}" "${2}" "${3}" + fi + Debug "executed backup-${1} script" +} + +# hourly backup +if [ ${isHourly} == true ]; then + if [ ${doHourly} == true ]; then + # run backup + RunBackup "hourly" "${newHourly}" "${oldHourly}" else - # write to logfiles that it's disabled - CheckDebug "info: backup-daily is disabled" - echo "info: backup-daily is disabled" >> ${backuplog} - echo "" >> ${backuplog} + Log "info" "backup-hourly is disabled" "${backupLog}" + Print "info" "backup-hourly is disabled" fi fi - -# check if it is the right time and weekday -if [ ${hours} -eq ${dailybackuptime} ] && [ ${weekday} -eq ${weeklybackupday} ]; then - - # write date and execute into logfiles - echo "action: ${date} executing backup-weekly script" >> ${screenlog} - echo "action: ${date} executing backup-weekly script" >> ${backuplog} - CheckDebug "executing backup-weekly script" - - # check if weekly backups are enabled - if [ ${doweekly} = true ]; then - - # start milliseconds timer - before=$(date +%s%3N) - - # checks for the existence of a screen terminal - if ! screen -list | grep -q "\.${servername}"; then - echo "${yellow}server is not currently running!${nocolor}" - echo "info: server is not currently running!" >> ${screenlog} - echo "info: server is not currently running!" >> ${backuplog} - echo "" >> ${backuplog} - exit 1 - fi - - # check if world is bigger than diskspace - if (( (${absoluteworldsize} + ${diskspacepadding}) > ${absolutediskspace} )); then - # ingame, terminal and logfile error output - PrintToScreenNotEnoughtDiskSpace "${newweekly}" "${oldweekly}" - PrintToLogNotEnoughDiskSpace "weekly" - PrintToTerminalNotEnoughDiskSpace "weekly" - CheckDebug "backup script reports not enough disk-space while performing backup-weekly" - exit 1 - fi - - # check if disk space is getting low - if (( (${absoluteworldsize} + ${diskspacewarning}) > ${absolutediskspace} )); then - PrintToScreenDiskSpaceWarning "${newweekly}" "${oldweekly}" - PrintToLogDiskSpaceWarning - PrintToTerminalDiskSpaceWarning - CheckDebug "backup script reports low disk-space while performing backup-weekly" - fi - - # check if there is no backup from the current week - if ! [[ -s "${backupdirectory}/weekly/${servername}-${newweekly}.tar.gz" ]]; then - if [[ -s "world.tar.gz" ]]; then - rm world.tar.gz - fi - PrintToScreen "save-off" - tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/weekly/${servername}-${newweekly}.tar.gz - PrintToScreen "save-on" - else - PrintToScreenBackupAlreadyExists "${newweekly}" "${oldweekly}" - PrintToLogBackupAlreadyExists "weekly" - PrintToTerminalBackupAlreadyExists "weekly" - CheckDebug "backup script reports backup already exists while performing backup-weekly" - exit 1 - fi - - # check if there is a new backup - if [[ -s "${backupdirectory}/weekly/${servername}-${newweekly}.tar.gz" ]]; then - # check if an old backup exists an remove it - if [[ -s "${backupdirectory}/weekly/${servername}-${oldweekly}.tar.gz" ]]; then - rm ${backupdirectory}/weekly/${servername}-${oldweekly}.tar.gz - fi - # stop milliseconds timer - after=$(date +%s%3N) - # calculate time spent on backup process - timespent=$((${after}-${before})) - # get compressed backup size - compressedbackup=$(du -sh ${backupdirectory}/weekly/${servername}-${newweekly}.tar.gz | cut -f1) - # read server.settings file again - . ./server.settings - # ingame and logfile success output - PrintToScreenBackupSuccess "${newweekly}" "${oldweekly}" - PrintToLogBackupSuccess "${newweekly}" "${oldweekly}" - PrintToTerminalBackupSuccess "${newweekly}" "${oldweekly}" - CheckDebug "backup script reports backup success while performing backup-weekly" - else - # ingame and logfile error output - PrintToScreenBackupError "${newweekly}" "${oldweekly}" - PrintToLogBackupError - PrintToTerminalBackupError - CheckDebug "backup script reports backup error while performing backup-weekly" - fi - +# daily backup +if [ ${isDaily} == true ]; then + if [ ${doDaily} == true ]; then + # run backup + RunBackup "daily" "${newDaily}" "${oldDaily}" else - # write to logfiles that it's disabled - CheckDebug "info: backup-weekly is disabled" - echo "info: backup-weekly is disabled" >> ${backuplog} - echo "" >> ${backuplog} + Log "info" "backup-daily is disabled" "${backupLog}" + Print "info" "backup-daily is disabled" fi fi +# weekly backup +if [ ${isWeekly} == true ]; then + if [ ${doWeekly} == true ]; then + # run backup + RunBackup "weekly" "${newWeekly}" "${oldWeekly}" + else + Log "info" "backup-weekly is disabled" "${backupLog}" + Print "info" "backup-weekly is disabled" + fi +fi -# check if it is the right time and day of the month -if [ ${hours} -eq ${dailybackuptime} ] && [ ${dayofmonth} -eq ${monthlybackupday} ]; then - - # write date and execute into logfiles - echo "action: ${date} executing backup-monthly script" >> ${screenlog} - echo "action: ${date} executing backup-monthly script" >> ${backuplog} - CheckDebug "executing backup-monthly script" - - # check if monthly backups are enabled - if [ ${domonthly} = true ]; then - - # start milliseconds timer - before=$(date +%s%3N) - - # checks for the existence of a screen terminal - if ! screen -list | grep -q "\.${servername}"; then - echo "${yellow}server is not currently running!${nocolor}" - echo "info: server is not currently running!" >> ${screenlog} - echo "info: server is not currently running!" >> ${backuplog} - echo "" >> ${backuplog} - exit 1 - fi - - # check if world is bigger than diskspace - if (( (${absoluteworldsize} + ${diskspacepadding}) > ${absolutediskspace} )); then - # ingame, terminal and logfile error output - PrintToScreenNotEnoughtDiskSpace "${newmonthly}" "${oldmonthly}" - PrintToLogNotEnoughDiskSpace "monthly" - PrintToTerminalNotEnoughDiskSpace "monthly" - CheckDebug "backup script reports not enough disk-space while performing backup-monthly" - exit 1 - fi - - # check if disk space is getting low - if (( (${absoluteworldsize} + ${diskspacewarning}) > ${absolutediskspace} )); then - PrintToScreenDiskSpaceWarning "${newmonthly}" "${oldmonthly}" - PrintToLogDiskSpaceWarning - PrintToTerminalDiskSpaceWarning - CheckDebug "backup script reports low disk-space while performing backup-monthly" - fi - - # check if there is no backup from the current month - if ! [[ -s "${backupdirectory}/monthly/${servername}-${newmonthly}.tar.gz" ]]; then - if [[ -s "world.tar.gz" ]]; then - rm world.tar.gz - fi - PrintToScreen "save-off" - tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/monthly/${servername}-${newmonthly}.tar.gz - PrintToScreen "save-on" - else - PrintToScreenBackupAlreadyExists "${newmonthly}" "${oldmonthly}" - PrintToLogBackupAlreadyExists "monthly" - PrintToTerminalBackupAlreadyExists "monthly" - CheckDebug "backup script reports backup already exists while performing backup-monthly" - exit 1 - fi - - # check if there is a new backup - if [[ -s "${backupdirectory}/monthly/${servername}-${newmonthly}.tar.gz" ]]; then - # check if an old backup exists an remove it - if [[ -s "${backupdirectory}/monthly/${servername}-${oldmonthly}.tar.gz" ]]; then - rm ${backupdirectory}/monthly/${servername}-${oldmonthly}.tar.gz - fi - # stop milliseconds timer - after=$(date +%s%3N) - # calculate time spent on backup process - timespent=$((${after}-${before})) - # get compressed backup size - compressedbackup=$(du -sh ${backupdirectory}/monthly/${servername}-${newmonthly}.tar.gz | cut -f1) - # read server.settings file again - . ./server.settings - # ingame and logfile success output - PrintToScreenBackupSuccess "${newmonthly}" "${oldmonthly}" - PrintToLogBackupSuccess "${newmonthly}" "${oldmonthly}" - PrintToTerminalBackupSuccess "${newmonthly}" "${oldmonthly}" - CheckDebug "backup script reports backup success while performing backup-monthly" - else - # ingame and logfile error output - PrintToScreenBackupError "${newmonthly}" "${oldmonthly}" - PrintToLogBackupError - PrintToTerminalBackupError - CheckDebug "backup script reports backup error while performing backup-monthly" - fi - +# monthly backup +if [ ${isMonthly} == true ]; then + if [ ${doMonthly} == true ]; then + # run backup + RunBackup "monthly" "${newMonthly}" "${oldMonthly}" else - # write to logfiles that it's disabled - CheckDebug "info: backup-monthly is disabled" - echo "info: backup-monthly is disabled" >> ${backuplog} - echo "" >> ${backuplog} + Log "info" "backup-monthly is disabled" "${backupLog}" + Print "info" "backup-monthly is disabled" fi fi +# debug +Debug "executed $0 script" + # exit with code 0 exit 0 diff --git a/maintenance.sh b/maintenance.sh deleted file mode 100644 index 0c48b46..0000000 --- a/maintenance.sh +++ /dev/null @@ -1,120 +0,0 @@ -#!/bin/bash -# minecraft server maintenance script - -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi - -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi - -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi - -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi - -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi - -# log to debug if true -CheckDebug "executing maintenance script" - -# parsing script arguments -ParseScriptArguments "$@" - -# write date to logfile -echo "action: ${date} executing maintenance script" >> ${screenlog} - -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - echo "${yellow}server is not currently running!${nocolor}" - exit 1 -fi - -# check if immediately is specified -if ! [[ ${immediately} == true ]]; then - # countdown - counter="60" - while [ ${counter} -gt 0 ]; do - if [[ "${counter}" =~ ^(60|40|20|10|5|4|3|2|1)$ ]];then - echo "${blue}[Script]${nocolor} server is going into maintenance in ${counter} seconds" - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"server is going into maintenance in ${counter} seconds\"}]$(printf '\r')" - fi - counter=$((counter-1)) - sleep 1s - done -fi - -# server stop -CheckQuiet "${cyan}action: stopping server...${nocolor}" -PrintToScreen "say stopping server..." -PrintToScreen "stop" - -# check if server stopped -stopchecks="0" -while [ $stopchecks -lt 30 ]; do - if ! screen -list | grep -q "\.${servername}"; then - break - fi -stopchecks=$((stopchecks+1)) -sleep 1s -done - -# force quit server if not stopped -if screen -list | grep -q "${servername}"; then - echo "${yellow}minecraft server still hasn't closed after 30 seconds, closing screen manually${nocolor}" - screen -S ${servername} -X quit -fi - -# output confirmed stop -echo "${green}server successfully stopped!${nocolor}" - -# remove all older safety backups -if [[ -s "${backupdirectory}/cached/maintenance-"* ]]; then - rm ${backupdirectory}/cached/maintenance-* -fi - -# create backup -echo "${blue}backing up...${nocolor}" -tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/cached/maintenance-${newdaily}.tar.gz - -# check if safety backup exists -if ! [[ -s "${backupdirectory}/cached/maintenance-${newdaily}.tar.gz" ]]; then - echo "${yellow}warning: safety backup failed - proceeding to server maintenance${nocolor}" - echo "warning: safety backup failed - proceeding to server maintenance" >> ${screenlog} -else - echo "ok: created ${backupdirectory}/cached/maintenance-${newdaily}.tar.gz as a safety backup" >> ${backuplog} - echo "" >> ${backuplog} - echo "have fun with maintenance ;^)" -fi - -# log to debug if true -CheckDebug "executed maintenance script" - -# exit with code 0 -exit 0 diff --git a/prerender.sh b/prerender.sh deleted file mode 100644 index 9837516..0000000 --- a/prerender.sh +++ /dev/null @@ -1,341 +0,0 @@ -#!/bin/bash -# mincraft server prerender script - -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi - -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi - -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi - -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi - -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi - -# log to debug if true -CheckDebug "executing prerender script" - -# parsing script arguments -ParseScriptArguments "$@" - -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - echo "${yellow}Server is not currently running!${nocolor}" - exit 1 -fi - -# let user chose between online and offline prerendering -echo "Would you like to startup online or offline prerendering?" -PS3="Your choice: " -method=("online" "offline") -select method in "${method[@]}"; do - case $method in - "online") - echo "action ${cyan}starting online prerenderer...${nocolor}" - - # explain to user - echo "${blue}I will prerender your minecraft world by teleporting a selected player through it${nocolor}" - echo "${blue}I will scan so to speak in a grid with the spacing of 256 blocks${nocolor}" - - # ask for playername - read -p "Please enter a playername: " playername - echo "The player will be ${green}${playername}${nocolor}" - - # ask for cords - PS3="Which radius would you like to prerender? " - grid=("1024*1024" "2048*2048" "4096*4096" "8192*8192") - select grid in "${grid[@]}"; do - case $grid in - "1024*1024") - cords=( 1024 768 512 256 0 -256 -512 -768 -1024 ) - area="1024 times 1024" - totalblocks=$((2048 * 2048)) - amount="9" - break - ;; - "2048*2048") - cords=( 2048 1792 1536 1280 1024 768 512 256 0 -256 -512 -768 -1024 -1280 -1536 -1792 -2048 ) - area="2048 times 2048" - totalblocks=$((4096 * 4096)) - amount="17" - break - ;; - "4096*4096") - cords=( 4096 3840 3584 3328 3072 2816 2560 2304 2048 1792 1536 1280 1024 768 512 256 0 -256 -512 -768 -1024 -1280 -1536 -1792 -2048 -2304 -2560 -2816 -3072 -3328 -3584 -3840 -4096 ) - area="4096 times 4096" - totalblocks=$((8192 * 8192)) - amount="33" - break - ;; - "8192*8192") - cords=( 8192 7936 7680 7414 7168 6912 6656 6400 6144 5888 5632 5376 5120 4864 4608 4352 4096 3840 3584 3328 3072 2816 2560 2304 2048 1792 1536 1280 1024 768 512 256 0 -256 -512 -768 -1024 -1280 -1536 -1792 -2048 -2304 -2560 -2816 -3072 -3328 -3584 -3840 -4096 -4352 -4608 -4864 -5120 -5376 -5632 -5888 -6144 -6400 -6656 -6912 -7168 -7414 -7680 -7936 -8192 ) - area="8192 times 8192" - totalblocks=$((16384 * 16384)) - amount="65" - break - ;; - *) echo "Please choose an option from the list: " ;; - esac - done - - # ask for interval in seconds - echo "I would like to know how fast you want to scan your world" - echo "I would recommend an interval of 20 to 80 seconds depending on your server recources" - echo "Please enter an interval in seconds. Example: ${yellow}60${nocolor}" - read -p "interval: " interval - regex="^([8-9]|[1-9][0-9]|1[0-2][0-8])$" - while [[ ! ${interval} =~ ${regex} ]]; do - read -p "Please enter an interval between 8 and 128 seconds: " interval - done - - # calculate some internal intervals - between=$((${interval} / 4)) - between="sleep ${between}s" - estimated=$((${interval} * ${amount} * ${amount})) - interval="sleep ${interval}s" - echo "The selected grid will be ${green}${area}${nocolor}" - echo "The selected interval will be ${green}${interval}${nocolor}" - echo "The selected between will be ${green}${between}${nocolor}" - - # ask for permission to proceed - echo "I will now start to teleport the selected player through the world" - echo "It will take about ${estimated} seconds to finish prerendering" - read -p "Continue? [Y/N]: " - regex="^(Y|y|N|n)$" - while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY - done - if [[ ${REPLY} =~ ^[Yy]$ ]] - then echo "${green}starting prerenderer...${nocolor}" - else echo "${red}exiting...${nocolor}" - exit 1 - fi - - # prerender start - echo "Prerendering started" - echo "Progress: [0/$((${amount} * ${amount}))]" - sleep 2s - - # teleport script with progress - totalamount=$((${amount} * ${amount})) - progress="1" - counter="1" - y="120" - for x in "${cords[@]}"; do - for z in "${cords[@]}"; do - let "progress=counter" - # progress counter - ProgressBar "${blue}[Script]${nocolor} Progress: [${progress}/${totalamount}]" "${progress}" "${totalamount}" - # teleporting with facing directions - PrintToScreen "tp ${playername} ${x} ${y} ${z} 0 0" - ${between} - PrintToScreen "tp ${playername} ${x} ${y} ${z} 90 0" - ${between} - PrintToScreen "tp ${playername} ${x} ${y} ${z} 180 0" - ${between} - PrintToScreen "tp ${playername} ${x} ${y} ${z} 270 0" - ${between} - counter=$((counter+1)) - done - done - - # command line finished message - PrintToScreen "say Prerendering of your world has finished" - echo "${blue}[Script]${nocolor} ${green}Prerendering of your world has finished${nocolor}" - - echo "${blue}[Script]${nocolor} ${green}Rendered ${totalblocks} [${area}] blocks of area${nocolor}" - - # kick player with finished message - screen -Rd ${servername} -X stuff "kick ${playername} prerendering of your world has finished$(printf '\r')" - - ;; - "offline") - echo "${magenta}starting offline prerenderer...${nocolor}" - - # explain to user - echo "${blue}I will prerender your minecraft world by setting the worldspawn to various cordinates and then restarting the server over and over${nocolor}" - echo "${blue}I will scan so to speak in a grid with the spacing of 256 blocks${nocolor}" - - # ask for cords - PS3="Which radius would you like to prerender? " - grid=("1024*1024" "2048*2048" "4096*4096" "8192*8192") - select grid in "${grid[@]}"; do - case $grid in - "1024*1024") - cords=( 1024 768 512 256 0 -256 -512 -768 -1024 ) - area="1024 times 1024" - totalblocks=$((2048 * 2048)) - amount="9" - break - ;; - "2048*2048") - cords=( 2048 1792 1536 1280 1024 768 512 256 0 -256 -512 -768 -1024 -1280 -1536 -1792 -2048 ) - area="2048 times 2048" - totalblocks=$((4096 * 4096)) - amount="17" - break - ;; - "4096*4096") - cords=( 4096 2048 1792 1536 1280 1024 768 512 256 0 -256 -512 -768 -1024 -1280 -1536 -1792 -2048 -4096 ) - area="4096 times 4096" - totalblocks=$((8192 * 8192)) - amount="33" - break - ;; - "8192*8192") - cords=( 8192 6144 4096 2048 1792 1536 1280 1024 768 512 256 0 -256 -512 -768 -1024 -1280 -1536 -1792 -2048 -4096 -6144 -8192 ) - area="8192 times 8192" - totalblocks=$((16384 * 16384)) - amount="65" - break - ;; - *) echo "Please choose an option from the list: " ;; - esac - done - - # ask for interval in seconds - echo "I would like to know how fast you want to scan your world" - echo "I would recommend an interval of 20 to 80 seconds depending on your server recources" - echo "Please enter an interval in seconds. Example: ${yellow}60${nocolor}" - read -p "interval: " interval - regex="^([8-9]|[1-9][0-9]|1[0-2][0-8])$" - while [[ ! ${interval} =~ ${regex} ]]; do - read -p "Please enter an interval between 8 and 128 seconds: " interval - done - interval="sleep ${interval}s" - - # ask for permission to proceed - echo "I will now start to prerender your world using worldspawns and server restart" - read -p "Continue? [Y/N]: " - regex="^(Y|y|N|n)$" - while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY - done - if [[ ${REPLY} =~ ^[Yy]$ ]] - then echo "${green}starting prerenderer...${nocolor}" - else echo "${red}exiting...${nocolor}" - exit 1 - fi - - # prerender start - echo "Prerendering started" - echo "Progress: [0/$((${amount} * ${amount}))]" - sleep 2s - - # teleport script with progress - progress="1" - counting="1" - y="120" - for x in "${cords[@]}"; do - for z in "${cords[@]}"; do - let "progress=counting" - # progress counter - echo "${blue}[Script]${nocolor} Progress: [${progress}/$((${amount} * ${amount}))]" - # setworldspawn to x y z - PrintToScreen "setworldspawn ${x} ${y} ${z}" - # server stop - screen -Rd ${servername} -X stuff "say stopping server...$(printf '\r')" - screen -Rd ${servername} -X stuff "stop$(printf '\r')" - # check if server stopped - stopchecks="0" - while [ $stopchecks -lt 10 ]; do - if ! screen -list | grep -q "\.${servername}"; then - break - fi - stopchecks=$((stopchecks+1)) - sleep 1s - done - # force quit server if not stopped - if screen -list | grep -q "${servername}"; then - screen -S ${servername} -X quit - fi - ${interval} - # main start commmand - ${screen} -dmSL ${servername} -Logfile ${screenlog} ${java} -server ${mems} ${memx} ${threadcount} -jar ${serverfile} - ${screen} -r ${servername} -X colon "logfile flush 1^M" - # check if screenlog contains start comfirmation - count="0" - counter="0" - startupchecks="0" - while [ ${startupchecks} -lt 120 ]; do - if tail ${screenlog} | grep -q "Query running on"; then - break - fi - if ! screen -list | grep -q "${servername}"; then - echo "Fatal: something went wrong - server appears to have crashed!" >> ${screenlog} - echo "${red}Fatal: something went wrong - server appears to have crashed!${nocolor}" - exit 1 - fi - if tail ${screenlog} | grep -q "Preparing spawn area"; then - counter=$((counter+1)) - fi - if tail ${screenlog} | grep -q "Environment"; then - count=$((count+1)) - fi - if tail ${screenlog} | grep -q "Reloading ResourceManager"; then - count=$((count+1)) - fi - if tail ${screenlog} | grep -q "Starting minecraft server"; then - count=$((count+1)) - fi - if [ ${counter} -ge 10 ]; then - counter="0" - fi - if [ ${count} -eq 0 ] && [ ${startupchecks} -eq 20 ]; then - echo "Warning: the server could be crashed" >> ${screenlog} - echo "${yellow}Warning: the server could be crashed${nocolor}" - exit 1 - fi - startupchecks=$((startupchecks+1)) - sleep 1s - done - counting=$((counting+1)) - ${interval} - done - done - - # reset spawnpoint - PrintToScreen "setworldspawn 0 100 0" - - # command line info - echo "${green}Prerendering of your world has finished${nocolor}" - - ;; - *) echo "Please choose an option from the list: " ;; - esac -done - -# log to debug if true -CheckDebug "executed prerender script" - -# exit with code 0 -exit 0 diff --git a/reset.sh b/reset.sh index 60c3eef..c8f627b 100644 --- a/reset.sh +++ b/reset.sh @@ -1,131 +1,60 @@ #!/bin/bash # minecraft server reset script -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi - -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi - -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi - -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi - -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi +# read server files +source server.settings +source server.functions -# log to debug if true -CheckDebug "executing reset script" - -# parsing script arguments -ParseScriptArguments "$@" - -# write date to logfile -echo "action: ${date} executing reset script" >> ${screenlog} - -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - echo "server is not currently running!" >> ${screenlog} - echo "${yellow}server is not currently running!${nocolor}" - exit 1 -fi - -# check if immediately is specified -if ! [[ ${immediately} == true ]]; then - # countdown - counter="60" - while [ ${counter} -gt 0 ]; do - if [[ "${counter}" =~ ^(60|40|20|10|5|4|3|2|1)$ ]];then - echo "${blue}[Script]${nocolor} server is resetting in ${counter} seconds" - screen -Rd ${servername} -X stuff "gamemode spectator @a$(printf '\r')" - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"server is resetting in ${counter} seconds\"}]$(printf '\r')" - fi - counter=$((counter-1)) - sleep 1s - done -fi +# parse arguments +ParseArgs "$@" +ArgHelp + +# safety checks +RootSafety +ScriptSafety + +# debug +Debug "executing $0 script" + +# change to server directory +ChangeServerDirectory + +# check for existance of executable +CheckExecutable + +# look if server is running +CheckScreen + +# prints countdown to screen +Countdown "stopping" # server stop -CheckQuiet "${cyan}action: stopping server...${nocolor}" -PrintToScreen "say stopping server..." -PrintToScreen "stop" - -# check if server stopped -stopchecks="0" -while [ $stopchecks -lt 30 ]; do - if ! screen -list | grep -q "\.${servername}"; then - break - fi -stopchecks=$((stopchecks+1)) -sleep 1; -done +Stop + +# awaits server stop +AwaitStop # force quit server if not stopped -if screen -list | grep -q "${servername}"; then - echo "${yellow}minecraft server still hasn't closed after 30 seconds, closing screen manually${nocolor}" - screen -S ${servername} -X quit -fi +ForceQuit # output confirmed stop -echo "${green}server successfully stopped!${nocolor}" - -# remove al older safety backups -if [[ -s "${backupdirectory}/cached/reset-"* ]]; then - rm ${backupdirectory}/cached/reset-* -fi +Log "ok" "server successfully stopped" "${screenLog}" +Print "ok" "server successfully stopped" # create backup -echo "${blue}backing up...${nocolor}" -tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/cached/reset-${newdaily}.tar.gz - -# check if safety backup exists -if ! [[ -s "${backupdirectory}/cached/reset-${newdaily}.tar.gz" ]]; then - echo "${red}fatal: safety backup failed - can not proceed to remove world" - echo "fatal: safety backup failed - can not proceed to remove world" >> ${screenlog} - exit 1 -else - echo "created ${backupdirectory}/cached/reset-${newdaily}.tar.gz as a safety backup" >> ${backuplog} - echo "" >> ${backuplog} -fi +CachedBackup "reset" # remove log and world -echo "${red}removing world directory...${nocolor}" -rm -r world +Print "info" "removing world directory..." +nice -n 19 rm -r world mkdir world # restart the server -echo "${cyan}restarting server...${nocolor}" -./start.sh "$@" +echo "action" "restarting server..." +./start.sh --force "$@" # log to debug if true -CheckDebug "executed reset script" +Debug "executed $0 script" # exit with code 0 exit 0 diff --git a/restart.sh b/restart.sh index 8c82a84..7950208 100644 --- a/restart.sh +++ b/restart.sh @@ -1,105 +1,52 @@ #!/bin/bash # minecraft server restart script -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi +# read server files +source server.settings +source server.functions -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi +# parse arguments +ParseArgs "$@" +ArgHelp -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi +# safety checks +RootSafety +ScriptSafety -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi +# debug +Debug "executing $0 script" -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi +# change to server directory +ChangeServerDirectory -# log to debug if true -CheckDebug "executing restart script" - -# parsing script arguments -ParseScriptArguments "$@" +# check for existance of executable +CheckExecutable -# write date to logfile -echo "action: ${date} executing restart script" >> ${screenlog} +# look if server is running +CheckScreen -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - echo "${yellow}warning: server is not currently running!${nocolor}" - echo "${cyan}action: server not running - starting server now!${nocolor}" - echo "action: server not running - starting server now!" >> ${screenlog} - ./start.sh - exit 0 -fi - -# check if immediately is specified -if ! [[ ${immediately} == true ]]; then - # countdown - counter="60" - while [ ${counter} -gt 0 ]; do - if [[ "${counter}" =~ ^(60|40|20|10|5|4|3|2|1)$ ]];then - CheckQuiet "${blue}[Script]${nocolor} server is restarting in ${counter} seconds" - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"server is restarting in ${counter} seconds\"}]$(printf '\r')" - fi - counter=$((counter-1)) - sleep 1s - done -fi +# prints countdown to screen +Countdown "restarting" # server stop -CheckQuiet "${cyan}action: stopping server...${nocolor}" -PrintToScreen "say stopping server..." -PrintToScreen "stop" +Stop -# check if server stopped -stopchecks="0" -while [ $stopchecks -lt 30 ]; do - if ! screen -list | grep -q "\.${servername}"; then - break - fi - stopchecks=$((stopchecks+1)) - sleep 1; -done +# awaits server stop +AwaitStop # force quit server if not stopped -if screen -list | grep -q "${servername}"; then - echo "${yellow}warning: minecraft server still hasn't closed after 30 seconds, closing screen manually${nocolor}" - screen -S ${servername} -X quit -fi +ForceQuit + +# output confirmed stop +Log "ok" "server successfully stopped" "${screenLog}" +Print "ok" "server successfully stopped" # restart the server -CheckQuiet "${cyan}action: restarting server...${nocolor}" -./start.sh "$@" +Print "action" "restarting server..." +./start.sh --force "$@" # log to debug if true -CheckDebug "executed restart script" +Debug "executed $0 script" # exit with code 0 exit 0 diff --git a/restore.sh b/restore.sh index 55e3471..2fb2860 100644 --- a/restore.sh +++ b/restore.sh @@ -1,233 +1,159 @@ #!/bin/bash # minecraft server restore script -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi - -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi +# read server files +source server.settings +source server.functions -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi - -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi +# parse arguments +ParseArgs "$@" +ArgHelp -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi +# safety checks +RootSafety +ScriptSafety -# log to debug if true -CheckDebug "executing restore script" +# debug +Debug "executing $0 script" -# parsing script arguments -ParseScriptArguments "$@" +# change to server directory +ChangeServerDirectory -# write date to logfile -echo "action: ${date} executing restore script" >> ${screenlog} +# check for existance of executable +CheckExecutable -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - echo "server is not currently running!" >> ${screenlog} - echo "${yellow}server is not currently running!${nocolor}" - exit 1 -fi +# look if server is running +CheckScreen -# check if immediately is specified -if ! [[ ${immediately} == true ]]; then - # countdown - counter="60" - while [ ${counter} -gt 0 ]; do - if [[ "${counter}" =~ ^(60|40|20|10|5|4|3|2|1)$ ]];then - CheckQuiet "${blue}[Script]${nocolor} server is restoring a backup in ${counter} seconds" - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\",\"italic\":false},{\"text\":\"server is restoring a backup in ${counter} seconds\"}]$(printf '\r')" - fi - counter=$((counter-1)) - sleep 1s - done -fi +# prints countdown to screen +Countdown "restoring a backup" # server stop -CheckQuiet "stopping server..." -PrintToScreen "say stopping server..." -PrintToScreen "stop" - -# check if server stopped -stopchecks="0" -while [ $stopchecks -lt 30 ]; do - if ! screen -list | grep -q "\.${servername}"; then - break - fi - stopchecks=$((stopchecks+1)) - sleep 1; -done +Stop + +# awaits server stop +AwaitStop # force quit server if not stopped -if screen -list | grep -q "${servername}"; then - echo "${yellow}warning: minecraft server still hasn't closed after 30 seconds, closing screen manually${nocolor}" - screen -S ${servername} -X quit -fi +ForceQuit # output confirmed stop -echo "${green}server successfully stopped!${nocolor}" - -# remove all older safety backups -if [[ -s "${backupdirectory}/cached/restore-"* ]]; then - rm ${backupdirectory}/cached/restore-* -fi +Log "ok" "server successfully stopped" "${screenLog}" +Print "ok" "server successfully stopped" # create backup -echo "${blue}backing up...${nocolor}" -tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/cached/restore-${newdaily}.tar.gz - -# check if safety backup exists -if ! [[ -s "${backupdirectory}/cached/restore-${newdaily}.tar.gz" ]]; then - echo "${yellow}warning: safety backup failed - proceeding to server restore${nocolor}" - echo "warning: safety backup failed - proceeding to server restore" >> ${screenlog} -else - echo "info: created ${backupdirectory}/cached/restore-${newdaily}.tar.gz as a safety backup" >> ${backuplog} - echo "" >> ${backuplog} -fi +CachedBackup "restore" # create arrays with backupdirectorys -CheckVerbose "info: scanning backup directory..." -cd ${backupdirectory} +Print "info" "scanning backup directory..." +cd ${backupDirectory} backups=($(ls)) cd hourly -backupshourly=($(ls)) -cd ${backupdirectory} +backupsHourly=($(ls)) +cd ${backupDirectory} cd daily -backupsdaily=($(ls)) -cd ${backupdirectory} +backupsDaily=($(ls)) +cd ${backupDirectory} cd weekly -backupsweekly=($(ls)) -cd ${backupdirectory} +backupsWeekly=($(ls)) +cd ${backupDirectory} cd monthly -backupsmonthly=($(ls)) -cd ${backupdirectory} +backupsMonthly=($(ls)) +cd ${backupDirectory} cd cached -backupscached=($(ls)) -cd ${backupdirectory} +backupsCached=($(ls)) +cd ${backupDirectory} # ask for daily or hourly backup to restore -PS3="Would you like to restore a ${backups[0]}, ${backups[1]}, ${backups[2]}, ${backups[3]}, ${backups[4]}? " -select dailyhourlyweeklymonthly in "${backups[@]}" -do - echo "You chose: ${dailyhourlyweeklymonthly}" +PS3="$(date +"%H:%M:%S") prompt: would you like to restore a ${backups[0]}, ${backups[1]}, ${backups[2]}, ${backups[3]}, ${backups[4]} backup? " +select cachedDailyHourlyWeeklyMonthly in "${backups[@]}"; do + Print "info" "you chose: ${cachedDailyHourlyWeeklyMonthly}" break done # select specific backup out of daily, hourly, monthly, weekly or a special backup -if [[ "${dailyhourlyweeklymonthly}" == "${backups[0]}" ]] -then +if [[ "${cachedDailyHourlyWeeklyMonthly}" == "${backups[0]}" ]]; then # ask for cached backup - PS3="Which ${backups[4]} backup would you like to restore?" - select backup in "${backupscached[@]}" - do - echo "You chose: ${backup}" + PS3="$(date +"%H:%M:%S") prompt: which ${backups[4]} backup would you like to restore?" + select backup in "${backupsCached[@]}"; do + Print "info" "you chose: ${backup}" break done -elif [[ "${dailyhourlyweeklymonthly}" == "${backups[1]}" ]] -then +elif [[ "${cachedDailyHourlyWeeklyMonthly}" == "${backups[1]}" ]]; then # ask for daily backup - PS3="Which ${backups[0]} backup would you like to restore? " - select backup in "${backupsdaily[@]}" - do - echo "You chose: ${backup}" + PS3="$(date +"%H:%M:%S") prompt: which ${backups[0]} backup would you like to restore? " + select backup in "${backupsDaily[@]}"; do + Print "info" "you chose: ${backup}" break done -elif [[ "${dailyhourlyweeklymonthly}" == "${backups[2]}" ]] -then +elif [[ "${cachedDailyHourlyWeeklyMonthly}" == "${backups[2]}" ]]; then # ask for hourly backup - PS3="Which ${backups[1]} backup would you like to restore? " - select backup in "${backupshourly[@]}" - do - echo "You chose: ${backup}" + PS3="$(date +"%H:%M:%S") prompt: which ${backups[1]} backup would you like to restore? " + select backup in "${backupsHourly[@]}"; do + Print "info" "you chose: ${backup}" break done -elif [[ "${dailyhourlyweeklymonthly}" == "${backups[3]}" ]] -then +elif [[ "${cachedDailyHourlyWeeklyMonthly}" == "${backups[3]}" ]]; then # ask for monthly backup - PS3="Which ${backups[2]} backup would you like to restore? " - select backup in "${backupsmonthly[@]}" - do - echo "You chose: ${backup}" + PS3="$(date +"%H:%M:%S") prompt: which ${backups[2]} backup would you like to restore? " + select backup in "${backupsMonthly[@]}"; do + Print "info" "you chose: ${backup}" break done -elif [[ "${dailyhourlyweeklymonthly}" == "${backups[4]}" ]] -then +elif [[ "${cachedDailyHourlyWeeklyMonthly}" == "${backups[4]}" ]]; then # ask for weekly backup - PS3="Which ${backups[3]} backup would you like to restore? " - select backup in "${backupsweekly[@]}" - do - echo "You chose: ${backup}" + PS3="$(date +"%H:%M:%S") prompt: which ${backups[3]} backup would you like to restore? " + select backup in "${backupsWeekly[@]}"; do + Print "info" "you chose: ${backup}" break done fi -# echo selected backup -echo "selected backup to restore: ${backupdirectory}/${dailyhourlyweeklymonthly}/${backup}" - # ask for permission to proceed -echo "I will now delete the current world-directory and replace it with your chosen backup" -echo "You have chosen: ${backupdirectory}/${dailyhourlyweeklymonthly}/${backup} as a backup to restore" -read -p "Continue? [Y/N]: " +Print "info" "i will now delete the current world-directory and replace it with your chosen backup" +Print "info" "you have chosen: ${backupDirectory}/${cachedDailyHourlyWeeklyMonthly}/${backup} as a backup to restore" +read -p "$(date +"%H:%M:%S") prompt: continue? (y/n): " # if user replys yes perform restore +regex="^(Y|y|N|n)$" +while [[ ! ${REPLY} =~ ${regex} ]]; do + read -p "$(date +"%H:%M:%S") prompt: please press y or n: " REPLY +done if [[ ${REPLY} =~ ^[Yy]$ ]]; then - cd ${serverdirectory} - echo "${cyan}restoring backup...${nocolor}" - mv ${serverdirectory}/world ${serverdirectory}/old-world - cp ${backupdirectory}/${dailyhourlyweeklymonthly}/${backup} ${serverdirectory} - mv ${backup} world.tar.gz - tar -xf world.tar.gz - rm world.tar.gz + cd "${serverDirectory}" + Print "action" "restoring backup..." + nice -n 19 mv "${serverDirectory}/world" "${serverDirectory}/old-world" + nice -n 19 cp "${backupDirectory}/${cachedDailyHourlyWeeklyMonthly}/${backup}" "${serverDirectory}" + nice -n 19 mv "${backup}" "world.tar.gz" + nice -n 19 tar -xf "world.tar.gz" + nice -n 19 mv "tmp" "world" + nice -n 19 rm "world.tar.gz" if [ -d "world" ]; then - echo "${green}ok: restore successful${nocolor}" - echo "${cyan}action: restarting server with restored backup...${nocolor}" - echo "${date} the backup ${backupdirectory}/${dailyhourlyweeklymonthly}/${backup} has been restored" >> ${screenlog} - rm -r ${serverdirectory}/old-world + Log "the backup ${backupDirectory}/${cachedDailyHourlyWeeklyMonthly}/${backup} has been restored" "${screenLog}" + Print "ok" "restore successful" + Print "action" "restarting server with restored backup..." + nice -n 19 rm -r "${serverDirectory}/old-world" else - echo "${red}fatal: something went wrong - could not restore backup${nocolor}" - echo "fatal: something went wrong - could not restore backup" >> ${screenlog} - mv ${serverdirectory}/old-world ${serverdirectory}/world + Log "error" "something went wrong - could not restore backup" "${screenLog}" + Log "action" "reverting changes..." "${screenLog}" + Print "error" "something went wrong - could not restore backup" + Print "action" "reverting changes..." + nice -n 19 mv "${serverDirectory}/old-world" "${serverDirectory}/world" fi ./start.sh "$@" # if user replys no cancel and restart server -else cd ${serverdirectory} - echo "${yellow}warning: canceling backup restore...${nocolor}" - echo "${cyan}action: restarting server...${nocolor}" - echo "info: backup restore has been canceled" >> ${screenlog} - echo "info: resuming to current live world" >> ${screenlog} - ./start.sh "$@" +else + cd ${serverDirectory} + Print "warn" "backup restore has been canceled" + Print "info" "resuming to current live world" + Print "action" "restarting server..." + Log "info" "backup restore has been canceled" "${screenLog}" + Log "info" "resuming to current live world" "${screenLog}" + ./start.sh --force "$@" fi # log to debug if true -CheckDebug "executed restore script" +Debug "executed $0 script" # exit with code 0 exit 0 diff --git a/server.functions b/server.functions index cff8120..6724d61 100644 --- a/server.functions +++ b/server.functions @@ -1,414 +1,801 @@ #!/bin/bash -# minecraft server settings +# minecraft server functions # this file stores all the functions for the server. -# please notice that editing functions can have devastating effects +# please note that those function are global and impact every script. + +# please notice that editing these functions can be devastating # if you know what you are doing, feel free to tinker with them ;^) +# prints all input to log at given log level +function Log { + if [[ $1 == "ok" ]]; then + echo "$(date +"%Y-%m-%d %H:%M:%S") ok: ${2}" >>"${3}" + fi + if [[ $1 == "info" ]]; then + echo "$(date +"%Y-%m-%d %H:%M:%S") info: ${2}" >>"${3}" + fi + if [[ $1 == "warn" ]]; then + echo "$(date +"%Y-%m-%d %H:%M:%S") warn: ${2}" >>"${3}" + fi + if [[ $1 == "error" ]]; then + echo "$(date +"%Y-%m-%d %H:%M:%S") error: ${2}" >>"${3}" + fi + if [[ $1 == "fatal" ]]; then + echo "$(date +"%Y-%m-%d %H:%M:%S") fatal: ${2}" >>"${3}" + fi + if [[ $1 == "action" ]]; then + echo "$(date +"%Y-%m-%d %H:%M:%S") action: ${2}" >>"${3}" + fi +} + +# prints all input to terminal at given log level +function Print { + if [[ ${1} == "ok" ]] && [[ ${quiet} == false ]]; then + echo "$(date +"%H:%M:%S") ${green}ok${noColor}: ${2}" + fi + if [[ ${1} == "info" ]] && [[ ${quiet} == false ]]; then + echo "$(date +"%H:%M:%S") ${blue}info${noColor}: ${2}" + fi + if [[ ${1} == "warn" ]]; then + echo "$(date +"%H:%M:%S") ${yellow}warn${noColor}: ${2}" + fi + if [[ ${1} == "error" ]]; then + echo "$(date +"%H:%M:%S") ${red}error${noColor}: ${2}" + fi + if [[ ${1} == "fatal" ]]; then + echo "$(date +"%H:%M:%S") ${red}fatal${noColor}: ${2}" + fi + if [[ ${1} == "action" ]] && [[ ${quiet} == false ]]; then + echo "$(date +"%H:%M:%S") ${cyan}action${noColor}: ${2}" + fi + if [[ $1 == "debug" ]] && [[ ${quiet} == false ]]; then + echo "$(date +"%H:%M:%S") debug: ${2}" + fi +} + +# checks if debug mode is on +function Debug { + if [[ ${enableDebug} == true ]]; then + echo "$(date +"%Y-%m-%d %H:%M:%S") ${1}" >>"${debugLog}" + fi + if [[ ${verbose} == true ]]; then + Print "debug" "${1}" + fi +} + +# prints all input to screen +function Screen { + if screen -list | grep -q "\.${serverName}"; then + screen -Rd "${serverName}" -X stuff "${1}$(printf '\r')" + fi +} -# function for parsing arguments for a script -function ParseScriptArguments { - immediately=false +# function for parsing all arguments for a script +function ParseArgs { + force=false + help=false + now=false quiet=false verbose=false while [[ $# -gt 0 ]]; do - case "$1" in - -i) - immediately=true + case "${1}" in + -f) + force=true + ;; + -h) + help=true + ;; + -n) + now=true + ;; + -q) + quiet=true ;; - -q) - quiet=true + -v) + verbose=true ;; - -v) - verbose=true + --force) + force=true ;; - --immediately) - immediately=true + --help) + help=true ;; - --quiet) - quiet=true + --now) + now=true ;; - --verbose) - verbose=true + --quiet) + quiet=true ;; - *) - echo "bad argument: $1" - exit 1 + --verbose) + verbose=true + ;; + *) + Print "warn" "bad argument: ${1}" + Print "info" "for help use --help" ;; esac shift done } -# checks if debug is set to true and logs very verbose to debug.log -function CheckDebug { - if [[ ${enabledebug} == true ]]; then - echo "${date} ${1}" >> ${debuglog} + +function ParseCategory { + # standart values + isHourly=false + isDaily=false + isWeekly=false + isMonthly=false + # test and set backup category + if [[ $1 == "--hourly" ]]; then + isHourly=true + elif [[ $1 == "--daily" ]]; then + isDaily=true + elif [[ $1 == "--weekly" ]]; then + isWeekly=true + elif [[ $1 == "--monthly" ]]; then + isMonthly=true + else + Print "error" "\"$1\" is not a backup category" + Print "info" "use --hourly, --daily, --weekly, --monthly" + exit 1 fi } -# check if verbose mode is on -function CheckVerbose { - if [[ ${verbose} == true ]]; then - echo "${1}" + +# prints help and then exits +function ArgHelp { + if [[ ${help} == true ]]; then + Print "info" "available arguments:" + Print "info" "-f --force (ignores script safety checks)" + Print "info" "-h --help (prints this help page)" + Print "info" "-n --now (executes an action without countdown)" + Print "info" "-q --quiet (silences all output except warnings and errors)" + Print "info" "-v --verbose (prints more verbose and extra debug information)" + exit 0 fi } -# check if quiet mode is on -function CheckQuiet { - if ! [[ ${quiet} == true ]]; then - echo "${1}" + +# performs countdown +function Countdown { + if ! [[ ${now} == true ]]; then + counter=60 + while [ ${counter} -gt 0 ]; do + if [[ "${counter}" =~ ^(60|40|20|10|5|4|3|2)$ ]]; then + Print "info" "server is ${1} in ${counter} seconds" + TellrawScript "server is ${1} in ${counter} seconds" + fi + if [[ "${counter}" == 1 ]]; then + Print "info" "server is ${1} in ${counter} second" + TellrawScript "server is ${1} in ${counter} second" + fi + counter=$((counter - 1)) + sleep 1s + done fi } +# root safety check +function RootSafety { + if [ $(id -u) = 0 ]; then + Print "fatal" "please do not run me as root as this is dangerous :(" + exit 1 + fi +} -# prints all input to screen terminal -function PrintToScreen { - screen -Rd ${servername} -X stuff "${1}$(printf '\r')" +# checks if a script is already running +function ScriptSafety { + if [[ ${force} == false ]]; then + declare -a scriptsLock=("reset.sh" "restart.sh" "restore.sh" "start.sh" "stop.sh" "update.sh" "vent.sh") + scriptsLockLength=${#scriptsLock[@]} + for ((i = 0; i < ${scriptsLockLength}; i++)); do + for pid in $(pidof -x ${scriptsLock[i]}); do + if [ $pid != $$ ]; then + Print "warn" "script ${scriptsLock[i]} is already running" + Print "info" "use --force option to ignore this safety check" + exit 1 + fi + done + done + fi } +# checks and coordinates hourly daily weekly and monthly backup +# TODO: write function which prevents backups from happening simultaneous +function BackupSafety { + Print "info" "this function is still in development" + Print "info" "it does not execute anything at the moment" +} -# prints colourful success messages into screen -function PrintToScreenBackupSuccess { - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Backup] \",\"color\":\"gray\",\"italic\":true},{\"text\":\"successfully created new backup\",\"color\":\"green\",\"italic\":true,\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"created file: ${servername}-${1}.tar.gz, removed file: ${servername}-${2}.tar.gz, current world size: ${worldsize}, current backup size: ${backupsize}, current disk space: ${diskspace}, time spent: ${timespent} ms, compression: ${compressedbackup}/${worldsize}\"}]}}}]$(printf '\r')" +# check for existance of screen terminal +function CheckScreen { + if ! screen -list | grep -q "\.${serverName}"; then + Log "warn" "server is not currently running" >>"${screenLog}" + Print "warn" "server is not currently running" + exit 1 + fi } -# prints backup success to backup log -function PrintToLogBackupSuccess { - echo "ok: newest backup has been successfully created" >> ${backuplog} - echo "ok: added ${backupdirectory}/hourly/${servername}-${1}.tar.gz" >> ${backuplog} - echo "ok: oldest backup has been successfully removed" >> ${backuplog} - echo "ok: removed ${backupdirectory}/hourly/${servername}-${2}.tar.gz" >> ${backuplog} - echo "ok: current world size: ${worldsize}, current backup size: ${backupsize}, current disk space: ${diskspace}" >> ${backuplog} - echo "ok: time spent on backup process: ${timespent} milliseconds, compression ratio: ${compressedbackup}/${worldsize}" >> ${backuplog} - echo "" >> ${backuplog} + +# check for existance of screen terminal +function LookForScreen { + if screen -list | grep -q "\.${serverName}"; then + Log "warn" "server is already running" >>"${screenLog}" + Print "warn" "server is already running - type screen -r ${serverName} to open server terminal" + exit 1 + fi } -# prints success messages to terminal -function PrintToTerminalBackupSuccess { - CheckQuiet "${green}ok: newest backup has been successfully created${nocolor}" - CheckQuiet "${green}ok: added ${backupdirectory}/hourly/${servername}-${1}.tar.gz${nocolor}" - CheckQuiet "${green}ok: oldest backup has been successfully removed${nocolor}" - CheckQuiet "${green}ok: removed ${backupdirectory}/hourly/${servername}-${2}.tar.gz${nocolor}" - CheckVerbose "${green}ok: current world size: ${worldsize}, current backup size: ${backupsize}, current disk space: ${diskspace}${nocolor}" - CheckVerbose "${green}ok: time spent on backup process: ${timespent} milliseconds, compression ratio: ${compressedbackup}/${worldsize}${nocolor}" + +# check for executable +function CheckExecutable { + if ! ls ${executableServerFile}* 1>/dev/null 2>&1; then + Log "fatal" "no executable found" >>"${screenLog}" + Print "fatal" "no executable found" + exit 1 + fi } +# prints input to screen with script format +function TellrawScript { + if [[ $# -eq 1 ]]; then + Screen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"${1}\"}]" + else + Screen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"${1}\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"${2}\"}]}}}]" + fi +} + +# prints input to screen with backup format and color +function TellrawBackup { + if [[ $# -eq 2 ]]; then + Screen "tellraw @a [\"\",{\"text\":\"[Backup] \",\"color\":\"blue\"},{\"text\":\"${1}\",\"color\":\"${2}\"}]" + else + Screen "tellraw @a [\"\",{\"text\":\"[Backup] \",\"color\":\"blue\"},{\"text\":\"${1}\",\"color\":\"${2}\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"${3}\"}]}}}]" + fi +} -# prints colourful backup already exists message into screen -function PrintToScreenBackupAlreadyExists { - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Backup] \",\"color\":\"gray\",\"italic\":true},{\"text\":\"warning: backup already exists - please tell your server admin\",\"color\":\"yellow\",\"italic\":true,\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"could not create file: ${servername}-${1}.tar.gz, could not remove file: ${servername}-${2}.tar.gz, reason: backup already exists\"}]}}}]$(printf '\r')" +# prints input to screen at given player +function TellrawPlayer { + if [[ $# -eq 2 ]]; then + Screen "tellraw ${1} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"${2}\"}]" + else + Screen "tellraw ${1} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"${2} \"},{\"text\":\"${3}\",\"color\":\"${4}\"}]" + fi } -# prints backup already exists to backup log -function PrintToLogBackupAlreadyExists { - echo "warning: could not create new ${1}-backup" >> ${backuplog} - echo "warning: backup already exists" >> ${backuplog} - echo "" >> ${backuplog} + +# checks private network availability +function CheckPrivate { + privateChecks=0 + while [ ${privateChecks} -lt 8 ]; do + if ping -c 1 "${private}" &>/dev/null; then + Log "ok" "interface is online" "${screenLog}" + Print "ok" "interface is online" + break + else + Log "warn" "interface is offline" "${screenLog}" + Print "warn" "interface is offline" + fi + if [ ${privateChecks} -eq 7 ]; then + Log "error" "interface timed out" "${screenLog}" + Print "error" "interface timed out" + fi + sleep 1s + privateChecks=$((privateChecks + 1)) + done } -# prints backup already exists to terminal -function PrintToTerminalBackupAlreadyExists { - echo "${yellow}warning: could not create new ${1}-backup - backup already exists${nocolor}" + +# checks public network availability +function CheckPublic { + publicChecks=0 + while [ ${publicChecks} -lt 8 ]; do + if ping -c 1 "${public}" &>/dev/null; then + Log "ok" "nameserver is online" "${screenLog}" + Print "ok" "nameserver is online" + break + else + Log "warn" "nameserver is offline" "${screenLog}" + Print "warn" "nameserver is offline" + fi + if [ ${publicChecks} -eq 7 ]; then + Log "error" "nameserver timed out" "${screenLog}" + Print "error" "nameserver timed out" + fi + sleep 1s + publicChecks=$((publicChecks + 1)) + done +} + +# performs server start +function Start { + Print "action" "starting server..." + screen -dmSL "${serverName}" -Logfile "${screenLog}" java -server "${javaArgs}" -jar "${executableServerFile}" -nogui + screen -r "${serverName}" -X colon "logfile flush 1^M" +} + +# awaits server start +function AwaitStart { + startChecks=0 + while [ ${startChecks} -lt 10 ]; do + if screen -list | grep -q "\.${serverName}"; then + break + fi + startChecks=$((startChecks + 1)) + sleep 1s + done +} + +# performs server stop +function Stop { + Print "action" "stopping server..." + TellrawScript "stopping server..." + sleep 1s + Screen "stop" +} + +# awaits server stop +function AwaitStop { + stopChecks=0 + while [ ${stopChecks} -lt 20 ]; do + if ! screen -list | grep -q "\.${serverName}"; then + break + fi + stopChecks=$((stopChecks + 1)) + sleep 1 + done +} + +# conditional force quit +function ForceQuit { + if screen -list | grep -q "${serverName}"; then + Log "warn" "${serverName} server still hasn't closed after 30 seconds, closing screen manually..." "${screenLog}" + Print "warn" "${serverName} server still hasn't closed after 30 seconds, closing screen manually..." + screen -S "${serverName}" -X quit + fi +} + +# prints game over as pixel art on terminal +function GameOver { + echo "${red} ______ _____ ${noColor}" + echo "${red} / _____) / ___ \ ${noColor}" + echo "${red} | / ___ ____ ____ ____ | | | |_ _ ____ ____ ${noColor}" + echo "${red} | | (___)/ _ | \ / _ ) | | | | | | / _ )/ ___) ${noColor}" + echo "${red} | \____/( ( | | | | ( (/ / | |___| |\ V ( (/ /| | ${noColor}" + echo "${red} \_____/ \_||_|_|_|_|\____) \_____/ \_/ \____)_| ${noColor}" + echo "${red} ${noColor}" +} + +# declare all scripts in an array +declare -a scripts=("start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "worker.sh" "vent.sh") +# get length of script array +scriptsLength=${#scripts[@]} + +# function for removing scripts from serverdirectory +function RemoveScripts { + # remove scripts from serverdirectory + # loop through all entries in the array + Print "info" "removing scripts..." + for ((i = 0; i < ${scriptsLength}; i++)); do + Debug "removing script ${scripts[${i}]}" + rm "${scripts[${i}]}" + done } +# function for downloading scripts from github +function DownloadScripts { + # downloading scripts from github + # loop through all entries in the array + Print "info" "downloading scripts..." + for ((i = 0; i < ${scriptsLength}; i++)); do + Debug "downloading script ${scripts[${i}]} from branch ${branch} on github..." + wget -q -O "${scripts[${i}]}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${scripts[${i}]}" + done +} -# prints colorful disk space warning message into screen -function PrintToScreenDiskSpaceWarning { - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Backup] \",\"color\":\"gray\",\"italic\":true},{\"text\":\"warning: free disk space is getting rare - please tell your server admin\",\"color\":\"yellow\",\"italic\":true,\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"current world size: ${worldsize}, current backup size: ${backupsize}, current disk space: ${diskspace}, warning: free disk space is getting rare\"}]}}}]$(printf '\r')" +# function for making scripts executable +function ExecutableScripts { + # make selected scripts executable + # loop through all entries in the array + Print "info" "making scripts executable..." + for ((i = 0; i < ${scriptsLength}; i++)); do + Debug "setting script ${scripts[${i}]} executable" + chmod +x ${scripts[${i}]} + done } -# prints disk space warning to backup log -function PrintToLogDiskSpaceWarning { - echo "warning: free disk-space is getting rare" >> ${backuplog} + +# change to server directory with error checking +function ChangeServerDirectory { + if [ -d "${serverDirectory}" ]; then + cd ${serverDirectory} + else + Log "fatal" "server-directory is missing - path: ${serverDirectory}" "${screenLog}" + Print "fatal" "server-directory is missing - path: ${serverDirectory}" + exit 1 + fi } -# prints disk space warnig to terminal -function PrintToTerminalDiskSpaceWarning { - echo "${yellow}warning: free disk-space is getting rare${nocolor}" + +# change to backup directory with error checking +function ChangeBackupDirectory { + if [ -d "${backupDirectory}" ]; then + cd ${backupDirectory} + else + Log "fatal" "backup-directory is missing - path: ${backupDirectory}" "${screenLog}" + Print "fatal" "backup-directory is missing - path: ${backupDirectory}" + exit 1 + fi } +# prints success messages to terminal screen and backup log +function OutputBackupSuccess { + Log "ok" "added ${backupDirectory}/${1}/${serverName}-${2}.tar.gz" "${backupLog}" + Log "ok" "removed ${backupDirectory}/${1}/${serverName}-${3}.tar.gz" "${backupLog}" + Log "info" "current world size: ${worldSizeHuman}, current backup size: ${backupSizeHuman}, current disk space: ${diskSpaceHuman}" "${backupLog}" + Log "info" "time spent on backup process: ${timeSpent} milliseconds, compression ratio: ${compressedBackupSize}/${worldSizeHuman}" "${backupLog}" -# prints colourful not enough disk space message into screen -function PrintToScreenNotEnoughtDiskSpace { - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Backup] \",\"color\":\"gray\",\"italic\":true},{\"text\":\"fatal: not enough disk space - please immediately tell your server admin\",\"color\":\"red\",\"italic\":true,\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"could not create file: ${servername}-${1}.tar.gz, could not remove file: ${servername}-${2}.tar.gz, reason: not enough disk-space\"}]}}}]$(printf '\r')" + Print "ok" "added ${backupDirectory}/${1}/${serverName}-${2}.tar.gz" + Print "ok" "removed ${backupDirectory}/${1}/${serverName}-${3}.tar.gz" + Print "info" "current world size: ${worldSizeHuman}, current backup size: ${backupSizeHuman}, current disk space: ${diskSpaceHuman}" + Print "info" "time spent on backup process: ${timeSpent} milliseconds, compression ratio: ${compressedBackupSize}/${worldSizeHuman}" + + Debug "backup script reports backup success while performing backup-${1}" + + TellrawBackup "ok: successfully created new backup" "green" "created file: ${serverName}-${2}.tar.gz, removed file: ${serverName}-${3}.tar.gz, current world size: ${worldSizeHuman}, current backup size: ${backupSizeHuman}, current disk space: ${diskSpaceHuman}, time spent: ${timeSpent} ms, compression: ${compressedBackupSize}/${worldSizeHuman}" } -# prints not enough disk space to backup log -function PrintToLogNotEnoughDiskSpace { - echo "fatal: not enough disk-space to perform backup-${1}" >> ${backuplog} - echo "" >> ${backuplog} + +# prints disk space warning to terminal screen and backup log +function OutputDiskSpaceWarning { + Log "warn" "free disk-space is getting rare - make some room for backups" "${backupLog}" + Log "info" "available disk space ${diskSpaceHuman} - warning at: ${diskSpaceWarning} bytes, limit at: ${diskSpaceError} bytes" "${backupLog}" + + Print "warn" "free disk-space is getting rare - make some room for backups" + Print "info" "available disk space ${diskSpaceHuman} - warning at: ${diskSpaceWarning} bytes, limit at: ${diskSpaceError} bytes" + + Debug "backup script reports low disk-space while performing backup-${1}" + + TellrawBackup "warn: free disk space is getting rare - please tell your server admin" "yellow" "current world size: ${worldSizeHuman}, current backup size: ${backupSizeHuman}, current disk space: ${diskSpaceHuman}, warning: free disk space is getting rare" } -# prints not enough disk space to terminal -function PrintToTerminalNotEnoughDiskSpace { - echo "${red}fatal: not enough disk-space to perform backup-${1}${nocolor}" + +# prints backup size warning to terminal screen and backup log +function OutputBackupSizeWarning { + Log "warn" "the created ${1}-backup is only ${compressedBackupSize} - this may point to a corrupted backup" "${backupLog}" + Log "info" "you may change the control variables in the server.settings file - warning at: ${backupSizeWarning} percent, error at ${backupSizeError} percent" + + Print "warn" "the created ${1}-backup is only ${compressedBackupSize} - this may point to a corrupted backup" + Print "info" "you may change the control variables in the server.settings file - warning at: ${backupSizeWarning} percent, error at ${backupSizeError} percent" + + Debug "backup script reports potentially corrupted backup at ${backupDirectory}/${1}/${serverName}-${2}" + + TellrawBackup "warn: the created backup is unusally small - please tell your server admin" "yellow" "current world size: ${worldSizeHuman}, created backup size: ${compressedBackupSize}, warning: backup unusally small - this may point to corruption" } +# prints disk space error to terminal screen and backup log +function OutputDiskSpaceError { + Log "error" "not enough disk-space to perform backup-${1}" "${backupLog}" + Log "info" "available disk space ${diskSpaceHuman} - warning at: ${diskSpaceWarning} bytes, limit at: ${diskSpaceError} bytes" "${backupLog}" + + Print "error" "not enough disk-space to perform backup-${1}" + Print "info" "available disk space ${diskSpaceHuman} - warning at: ${diskSpaceWarning} bytes, limit at: ${diskSpaceError} bytes" -# prints colourful error messages into screen -function PrintToScreenBackupError { - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Backup] \",\"color\":\"gray\",\"italic\":true},{\"text\":\"fatal: could not create new backup - please immediately tell your server admin\",\"color\":\"red\",\"italic\":true,\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"could not create file: ${servername}-${1}.tar.gz, could not remove file: ${servername}-${2}.tar.gz, reason: missing directories, empty file-path or empty files\"}]}}}]$(printf '\r')" + Debug "backup script reports not enough disk-space while performing backup-${1}" + + TellrawBackup "fatal: not enough disk space - please immediately tell your server admin" "red" "could not create file: ${serverName}-${2}.tar.gz, could not remove file: ${serverName}-${3}.tar.gz, reason: not enough disk-space" } -# prints backup error to backup log -function PrintToLogBackupError { - echo "warning: cannot remove old backup because new backup is missing" >> ${backuplog} - echo "warning: could not remove old backup" >> ${backuplog} - echo "fatal: could not backup world" >> ${backuplog} - echo "" >> ${backuplog} + +# prints backup size error to terminal screen and backup log +function OutputBackupSizeError { + Log "error" "the created ${1}-backup is only ${compressedBackupSize} - this will point to a corrupted backup" "${backupLog}" + Log "info" "you may change the control variables in the server.settings file - warning at: ${backupSizeWarning} percent, error at ${backupSizeError} percent" + + Print "error" "the created ${1}-backup is only ${compressedBackupSize} - this will point to a corrupted backup" + Print "info" "you may change the control variables in the server.settings file - warning at: ${backupSizeWarning} percent, error at ${backupSizeError} percent" + + Debug "backup script reports dangerous corrupted backup at ${backupDirectory}/${1}/${serverName}-${2}" + + TellrawBackup "error: the created backup is too small - please tell your server admin" "red" "current world size: ${worldSizeHuman}, created backup size: ${compressedBackupSize}, reason: backup too small - this points to corruption" } -# prints backup error to backup log -function PrintToTerminalBackupError { - echo "${yellow}warning: cannot remove old backup because new backup is missing${nocolor}" - echo "${yellow}warning: could not remove old backup${nocolor}" - echo "${red}fatal: could not backup world${nocolor}" + +# prints backup already exists messages to terminal screen and backup log +function OutputBackupAlreadyExists { + Log "error" "could not create new ${1}-backup - backup already exists" "${backupLog}" + Log "info" "the file ${backupDirectory}/${1}/${serverName}-${2} already exists" + + Print "error" "could not create new ${1}-backup - backup already exists" + Print "info" "the file ${backupDirectory}/${1}/${serverName}-${2} already exists" + + Debug "backup script reports backup already exists while performing backup-${1}" + + TellrawBackup "error: backup already exists - please tell your server admin" "red" "could not create file: ${serverName}-${2}.tar.gz, could not remove file: ${serverName}-${3}.tar.gz, reason: backup already exists" } +# prints tar backup error messages to terminal screen and backup log +function OutputBackupTarError { + Log "error" "tar reports errors during compression of world directory" "${backupLog}" + + Print "error" "tar reports errors during compression of world directory" + + Debug "backup script reports tar error while performing backup-${1}" -# creates an archive from a directory with progress bar -function ArchiveDirectoryWithProgress { - echo "I will create a compressed archive for ${1}" - tar cf - ${1} -P | pv -s $(du -sb ${1} | awk '{print $1}') | gzip > ${1}.tar.gz + TellrawBackup "fatal: could not create new backup - please immediately tell your server admin" "red" "could not create file: ${serverName}-${2}.tar.gz, could not remove file: ${serverName}-${3}.tar.gz, reason: tar reports errors during compression of world directory" } -# extracts a directory from an archive with progress bar -function ExtractDirectoryWithProgress { - echo "I will extract the archive ${1}" - pv ${1}.tar.gz | tar -xz + +# prints copy backup error messages to terminal screen and backup log +function OutputBackupCopyError { + Log "error" "copy reports errors during copying of world directory" "${backupLog}" + + Print "error" "copy reports errors during copying of world directory" + + Debug "backup script reports copy error while performing backup-${1}" + + TellrawBackup "fatal: could not create new backup - please immediately tell your server admin" "red" "could not create file: ${serverName}-${2}.tar.gz, could not remove file: ${serverName}-${3}.tar.gz, reason: copy reports errors during copying of world directory" } +# prints generic backup error messages to terminal screen and backup log +function OutputBackupGenericError { + Log "error" "could not backup world" "${backupLog}" + + Print "error" "could not backup world" + + Debug "backup script reports generic backup error while performing backup-${1}" -# creates a Progressbar function -function ProgressBar { - # process data - let progress=(${2}*100/${3}*100)/100 - let done=(${progress}*4)/10 - let left=40-${done} - # build progressbar string lengths - fill=$(printf "%${done}s") - empty=$(printf "%${left}s") - # terminal output - printf "\r${1} [${fill// /#}${empty// /-}] ${progress}%% " + TellrawBackup "fatal: could not create new backup - please immediately tell your server admin" "red" "could not create file: ${serverName}-${2}.tar.gz, could not remove file: ${serverName}-${3}.tar.gz, reason: generic error - missing directories, empty file-paths or empty files" } # function for testing if all categories for backups exists if not create them also check for root backups directory -function CheckBackupDirectoryIntegrity { - cd ${serverdirectory} +function BackupDirectoryIntegrity { + cd ${serverDirectory} # check for root backup directory and create if missing - if ! ls ${backupdirectory} &> /dev/null; then - echo "fatal: the root-backupdirectory is missing - your backups are likely gone :(" >> ${backuplog} - echo "info: creating a new root-backupdirectory with name backups at ${serverdirectory}" >> ${backuplog} - echo "" >> ${backuplog} - echo "${red}fatal: the root-backupdirectory is missing - your backups are likely gone :(${nocolor}" - CheckVerbose "info: creating a new root-backupdirectory with name backups at ${serverdirectory}" + if ! ls ${backupDirectory} &>/dev/null; then + Log "error" "the root-backupdirectory is missing - your backups are likely gone :(" "${backupLog}" + Log "info" "creating a new root-backupdirectory with name backups at ${serverDirectory}" "${backupLog}" + Print "error" "the root-backupdirectory is missing - your backups are likely gone :(" + Print "info" "creating a new root-backupdirectory with name backups at ${serverDirectory}" + Screen "tellraw @a [\"\",{\"text\":\"[Backup] \",\"color\":\"blue\"},{\"text\":\"error: the root-backupdirectory is missing - your backups are likely gone :(\",\"color\":\"red\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"reason: backup directory integrity check reports that the root backup directory is missing - the root backup directory has been recreated\"}]}}}]" mkdir backups fi - declare -a backupcategories=( "cached" "hourly" "daily" "weekly" "monthly" ) - arraylenght=${#backupcategories[@]} - for (( i = 1; i < ${arraylenght} + 1; i ++ )); do + declare -a backupCategories=("cached" "hourly" "daily" "weekly" "monthly") + arrayLenght=${#backupCategories[@]} + for ((i = 0; i < ${arrayLenght}; i++)); do # check for backup category directories and create if missing - if ! ls ${backupdirectory}/${backupcategories[${i}-1]} &> /dev/null; then - echo "warning: the backup-directory ${backupcategories[${i}-1]} is missing" >> ${backuplog} - echo "info: creating ${backupdirectory}/${backupcategories[${i}-1]}" >> ${backuplog} - echo "" >> ${backuplog} - echo "${yellow}warning: the backup-directory ${backupcategories[${i}-1]} is missing${nocolor}" - CheckVerbose "info: creating ${backupdirectory}/${backupcategories[${i}-1]}" - cd ${backupdirectory} - mkdir ${backupcategories[${i}-1]} - cd ${serverdirectory} + if ! ls ${backupDirectory}/${backupCategories[${i}]} &>/dev/null; then + Log "warn" "the backup-directory ${backupCategories[${i}]} is missing" "${backupLog}" + Log "info" "creating ${backupDirectory}/${backupCategories[${i}]}" "${backupLog}" + Print "warn" "the backup-directory ${backupCategories[${i}]} is missing" + Print "info" "creating ${backupDirectory}/${backupCategories[${i}]}" + Screen "tellraw @a [\"\",{\"text\":\"[Backup] \",\"color\":\"blue\"},{\"text\":\"warn: the ${backupCategories[${i}]} backup category is missing - your ${backupCategories[${i}]} backups are likely gone :/\",\"color\":\"yellow\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"reason: backup directory integrity check reports that the ${backupCategories[${i}]} backup directory is missing - the ${backupCategories[${i}]} backup directory has been recreated\"}]}}}]" + cd ${backupDirectory} + mkdir ${backupCategories[${i}]} + cd ${serverDirectory} fi done } -# function for fetching scripts from github with error checking -function FetchScriptFromGitHub { - wget --spider --quiet https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${1} - if [ "$?" != 0 ]; then - echo "${red}fatal: Unable to connect to GitHub API. Script will exit! (maybe chose another branch?)${nocolor}" - exit 1 +# function for creating a cached backup with name as input +function CachedBackup { + # remove all older cached backups + if [[ -s "${backupDirectory}/cached/${1}-"* ]]; then + rm "${backupDirectory}/cached/${1}-"* + fi + # user info about backup to create + Print "action" "creating cached ${1} backup..." + # create backup with given name + nice -n 19 cp -r "world" "tmp-${1}" + nice -n 19 tar -czf "world.tar.gz" "tmp-${1}" + nice -n 19 mv "${serverDirectory}/world.tar.gz" "${backupDirectory}/cached/${1}-${newDaily}-${newHourly}.tar.gz" + nice -n 19 rm -r "tmp-${1}" + # check if safety backup exists + if [[ -s "${backupDirectory}/cached/${1}-${newDaily}-${newHourly}.tar.gz" ]]; then + Log "ok" "created ${backupDirectory}/cached/${1}-${newDaily}-${newHourly}.tar.gz as a ${1} backup" "${backupLog}" + + Print "ok" "${1} backup successful" + + TellrawBackup "ok: backup successful" "green" "created ${backupDirectory}/cached/${1}-${newDaily}-${newHourly}.tar.gz" else - CheckVerbose "info: fetching file: ${1} from branch ${branch} on GitHub..." - wget -q -O ${1} https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${1} -fi -} + Log "warn" "${1} backup failed" "${backupLog}" -# function for removing scripts from serverdirectory -function RemoveScriptsFromServerDirectory { - # user info about download - CheckVerbose "info: removing scripts in serverdirectory... " - # remove scripts from serverdirectory - # declare all scripts in an array - declare -a scripts=( "LICENSE" "README.md" "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "maintenance.sh" "prerender.sh" "watchdog.sh" "welcome.sh" "worker.sh" "vent.sh" ) - # get length of script array - scriptslength=${#scripts[@]} - # loop through all entries in the array - for (( i = 1; i < ${scriptslength} + 1; i ++ )); do - CheckVerbose "info: removing script ${scripts[${i}-1]}" - rm "${scripts[${i}-1]}" - done + Print "warn" "${1} backup failed" + + TellrawBackup "warn: backup failed" "yellow" "failed to create ${backupDirectory}/cached/${1}-${newDaily}-${newHourly}.tar.gz" + fi } -# function for downloading scripts from github -function DownloadScriptsFromGitHub { - # user info about download - CheckVerbose "info: downloading scripts from GitHub... " - # downloading scripts from github - # declare all scripts in an array - declare -a scripts=( "LICENSE" "README.md" "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "maintenance.sh" "prerender.sh" "watchdog.sh" "welcome.sh" "worker.sh" "vent.sh" ) - # get length of script array - scriptslength=${#scripts[@]} - # loop through all entries in the array - for (( i = 1; i < ${scriptslength} + 1; i ++ )); do - FetchScriptFromGitHub "${scripts[${i}-1]}" - done +# check for help string +function Help { + if tail -1 "${screenLog}" | grep -q "help"; then + player=$(tail -1 screen.log | grep -oP '.*?(?=help)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') + Log "info" "the player ${player} requested help - server will print help info and admin contact" "${screenLog}" + TellrawPlayer "${player}" "info: available commands: (seperated by comma)" + TellrawPlayer "${player}" "info: list tasks, list backups" + TellrawPlayer "${player}" "info: perform backup, perform restart" + TellrawPlayer "${player}" "info: perform update, perform reset" + TellrawPlayer "${player}" "info: admin contact info: ${adminContact}" + fi } -# function for making scripts executable -function MakeScriptsExecutable { - # user info - CheckVerbose "ok: download successful" - # make selected scripts executable - # declare all scripts in an array - declare -a scripts=( "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "maintenance.sh" "prerender.sh" "watchdog.sh" "welcome.sh" "worker.sh" "vent.sh" ) - # get length of script array - scriptslength=${#scripts[@]} - # loop through all entries in the array - for (( i = 1; i < ${scriptslength} + 1; i ++ )); do - CheckVerbose "info: setting script ${scripts[${i}-1]} executable" - chmod +x ${scripts[${i}-1]} - done +# check for list tasks string +function ListTasks { + if tail -1 "${screenLog}" | grep -q "list tasks"; then + player=$(tail -1 screen.log | grep -oP '.*?(?=list tasks)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') + if cat "ops.json" | grep -q "${player}"; then + Log "info" "the player ${player} requested list of all tasks and has permission - server will list all tasks" "${screenLog}" + TellrawPlayer "${player}" "info: you successfully requested all available tasks of the server" + # run list tasks + if [[ ${enablePerformBackup} == true ]]; then + TellrawPlayer "${player}" "perform backup is" "enabled" "green" + elif [[ "${enablePerformBackup}" == false ]]; then + TellrawPlayer "${player}" "perform backup is" "disabled" "red" + else + TellrawPlayer "${player}" "perform backup is" "undefined" "grey" + fi + if [[ ${enablePerformRestart} == true ]]; then + TellrawPlayer "${player}" "perform restart is" "enabled" "green" + elif [[ "${enablePerformRestart}" == false ]]; then + TellrawPlayer "${player}" "perform restart is" "disabled" "red" + else + TellrawPlayer "${player}" "perform restart is" "undefined" "grey" + fi + if [[ ${enablePerformUpdate} == true ]]; then + TellrawPlayer "${player}" "perform update is" "enabled" "green" + elif [[ ${enablePerformUpdate} == false ]]; then + TellrawPlayer "${player}" "perform update is" "disabled" "red" + else + TellrawPlayer "${player}" "perform update is" "undefined" "grey" + fi + if [[ ${enablePerformReset} == true ]]; then + TellrawPlayer "${player}" "perform reset is" "enabled" "green" + elif [[ ${enablePerformReset} == false ]]; then + TellrawPlayer "${player}" "perform reset is" "disabled" "red" + else + TellrawPlayer "${player}" "perform reset is" "undefined" "grey" + fi + TellrawPlayer "${player}" "config is located in file server.settings" + else + Log "warn" "the player ${player} requested a list of tasks and does not have permission to do so" "${screenLog}" + TellrawPlayer "${player}" "warn: you do not have permissions to list all available tasks of the server" + fi + fi } -# function for creating a safety backup -function CreateSafetyBackup { - # remove all older safety backups - if [[ -s "${backupdirectory}/cached/safety-"* ]]; then - rm ${backupdirectory}/cached/safety-* +# check for list backups string +function ListBackups { + if tail -1 "${screenLog}" | grep -q "list backups"; then + player=$(tail -1 screen.log | grep -oP '.*?(?=list backups)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') + if cat "ops.json" | grep -q "${player}"; then + Log "info" "the player ${player} requested list of all backups and has permission - server will list all backups" "${screenLog}" + TellrawPlayer "${player}" "info: you successfully requested all available backups of the server" + # run list backups + if [[ ${doHourly} == true ]]; then + TellrawPlayer "${player}" "hourly backup is" "enabled" "green" + elif [[ "${doHourly}" == false ]]; then + TellrawPlayer "${player}" "hourly backup is" "disabled" "red" + else + TellrawPlayer "${player}" "hourly backup is" "undefined" "grey" + fi + if [[ ${doDaily} == true ]]; then + TellrawPlayer "${player}" "daily backup is" "enabled" "green" + elif [[ "${doDaily}" == false ]]; then + TellrawPlayer "${player}" "daily backup is" "disabled" "red" + else + TellrawPlayer "${player}" "daily backup is" "undefined" "grey" + fi + if [[ ${doWeekly} == true ]]; then + TellrawPlayer "${player}" "weekly backup is" "enabled" "green" + elif [[ ${doWeekly} == false ]]; then + TellrawPlayer "${player}" "weekly backup is" "disabled" "red" + else + TellrawPlayer "${player}" "weekly backup is" "undefined" "grey" + fi + if [[ ${doMonthly} == true ]]; then + TellrawPlayer "${player}" "monthly backup is" "enabled" "green" + elif [[ ${doMonthly} == false ]]; then + TellrawPlayer "${player}" "monthly backup is" "disabled" "red" + else + TellrawPlayer "${player}" "monthly backup is" "undefined" "grey" + fi + TellrawPlayer "${player}" "config is located in file server.settings" + else + Log "warn" "the player ${player} requested a list of backups and does not have permission to do so" "${screenLog}" + TellrawPlayer "${player}" "warn: you do not have permissions to list all available backups of the server" + fi fi - # create backup - echo "${blue}backing up...${nocolor}" - tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/cached/safety-${newdaily}-${newhourly}.tar.gz - # check if safety backup exists - if ! [[ -s "${backupdirectory}/cached/safety-${newdaily}-${newhourly}.tar.gz" ]]; then - # ingame output - PrintToScreen "tellraw @a [\"\",{\"text\":\"[Backup] \",\"color\":\"gray\",\"italic\":true},{\"text\":\"backup failed\",\"color\":\"red\",\"italic\":true,\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"file ${backupdirectory}/cached/safety-${newdaily}-${newhourly}.tar.gz does not exist\"}]}}}]" - # terminal output - echo "${yellow}warning: safety backup failed${nocolor}" - # logfile output - echo "warning: safety backup failed" >> ${backuplog} - echo "" >> ${backuplog} - else - # ingame output - PrintToScreen "tellraw @a [\"\",{\"text\":\"[Backup] \",\"color\":\"gray\",\"italic\":true},{\"text\":\"backup successful\",\"color\":\"green\",\"italic\":true,\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"created ${backupdirectory}/cached/safety-${newdaily}-${newhourly}.tar.gz\"}]}}}]" - # terminal output - echo "${green}ok: backup successful${nocolor}" - # logfile output - echo "ok: created ${backupdirectory}/cached/safety-${newdaily}-${newhourly}.tar.gz as a safety backup" >> ${backuplog} - echo "" >> ${backuplog} - fi -} - - -# check for safety backup string -function CheckSafetyBackupString { - if tail -1 "${screenlog}" | grep -q "perform safety backup"; then - player=$(tail -1 screen.log | grep -oP '.*?(?=perform safety backup)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') - if cat ops.json | grep -q "${player}"; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You successfully requested a safety backup of the server\"}]" - echo "info: The player ${player} requested a safety backup and has permission - server will perform safety backup" >> ${backuplog} - CreateSafetyBackup - sleep 20s +} + +# check for perform backup string +function PerformBackup { + if tail -1 "${screenLog}" | grep -q "perform backup"; then + player=$(tail -1 screen.log | grep -oP '.*?(?=perform backup)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') + if cat "ops.json" | grep -q "${player}"; then + Log "info" "the player ${player} requested a safety backup and has permission - server will perform safety backup" "${backupLog}" + TellrawPlayer "${player}" "info: you successfully requested a safety backup of the server\"}]" + # run safety backup + CachedBackup "safety" else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to safety backup the server\"}]" - echo "warning: The player ${player} requested a safety backup and does not have permission to do so" >> ${backuplog} - echo "" >> ${backuplog} + Log "warn" "the player ${player} requested a safety backup and does not have permission to do so" "${backupLog}" + TellrawPlayer "${player}" "warn: you do not have permissions to safety backup the server\"}]" fi fi } -# check for confirm restart strings -function CheckConfirmRestartString { + +# check for perform restart strings +function PerformRestart { # check for perform restart now string - if tail -1 "${screenlog}" | grep -q "perform restart now"; then + if tail -1 "${screenLog}" | grep -q "perform restart now"; then player=$(tail -1 screen.log | grep -oP '.*?(?=perform restart now)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') - if cat ops.json | grep -q "${player}"; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You successfully requested a restart of the server\"}]" - echo "info: The player ${player} requested a restart and has permission - server will restart" >> ${screenlog} - ./restart.sh --immediately + if cat "ops.json" | grep -q "${player}"; then + Log "info" "the player ${player} requested a restart and has permission - server will restart" "${screenLog}" + TellrawPlayer "${player}" "info: you successfully requested a restart of the server\"}]" + ./restart.sh --quiet --now exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to restart the server\"}]" - echo "warning: The player ${player} requested a restart and does not have permission to do so" >> ${screenlog} + Log "warn" "the player ${player} requested a restart and does not have permission to do so" "${screenLog}" + TellrawPlayer "${player}" "warn: you do not have permissions to restart the server\"}]" fi fi # check for perform restart string - if tail -1 "${screenlog}" | grep -q "perform restart"; then + if tail -1 "${screenLog}" | grep -q "perform restart"; then player=$(tail -1 screen.log | grep -oP '.*?(?=perform restart)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') - if cat ops.json | grep -q "${player}"; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You successfully requested a restart of the server\"}]" - echo "info: The player ${player} requested a restart and has permission - server will restart" >> ${screenlog} - ./restart.sh + if cat "ops.json" | grep -q "${player}"; then + Log "info" "the player ${player} requested a restart and has permission - server will restart" "${screenLog}" + TellrawPlayer "${player}" "info: you successfully requested a restart of the server\"}]" + ./restart.sh --quiet exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to restart the server\"}]" - echo "warning: The player ${player} requested a restart and does not have permission to do so" >> ${screenlog} + Log "warn" "the player ${player} requested a restart and does not have permission to do so" "${screenLog}" + TellrawPlayer "${player}" "warn: you do not have permissions to restart the server\"}]" fi fi } -# check for confirm update strings -function CheckConfirmUpdateString { + +# check for perform update strings +function PerformUpdate { # check for perform update now string - if tail -1 "${screenlog}" | grep -q "perform update now"; then + if tail -1 "${screenLog}" | grep -q "perform update now"; then player=$(tail -1 screen.log | grep -oP '.*?(?=perform update now)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') - if cat ops.json | grep -q "${player}"; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You successfully requested an update of the server\"}]" - echo "info: The player ${player} requested an update and has permission - server will update" >> ${screenlog} - ./update.sh --immediately + if cat "ops.json" | grep -q "${player}"; then + Log "info" "the player ${player} requested an update and has permission - server will update" "${screenLog}" + TellrawPlayer "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested an update of the server\"}]" + ./update.sh --quiet --now exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to update the server\"}]" - echo "warning: The player ${player} requested an update and does not have permission to do so" >> ${screenlog} + Log "warn" "the player ${player} requested an update and does not have permission to do so" "${screenLog}" + TellrawPlayer "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to update the server\"}]" fi fi # check for perform update string - if tail -1 "${screenlog}" | grep -q "perform update"; then + if tail -1 "${screenLog}" | grep -q "perform update"; then player=$(tail -1 screen.log | grep -oP '.*?(?=perform update)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') - if cat ops.json | grep -q "${player}"; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You successfully requested an update of the server\"}]" - echo "info: The player ${player} requested an update and has permission - server will update" >> ${screenlog} - ./update.sh + if cat "ops.json" | grep -q "${player}"; then + Log "info" "the player ${player} requested an update and has permission - server will update" "${screenLog}" + TellrawPlayer "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested an update of the server\"}]" + ./update.sh --quiet exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to update the server\"}]" - echo "warning: The player ${player} requested an update and does not have permission to do so" >> ${screenlog} + Log "warn" "the player ${player} requested an update and does not have permission to do so" "${screenLog}" + TellrawPlayer "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to update the server\"}]" fi fi } -# check for confirm reset strings -function CheckConfirmResetString { + +# check for perform reset strings +function PerformReset { # check for perform reset now string - if tail -1 "${screenlog}" | grep -q "perform reset now"; then + if tail -1 "${screenLog}" | grep -q "perform reset now"; then player=$(tail -1 screen.log | grep -oP '.*?(?=perform reset now)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') - if cat ops.json | grep -q "${player}"; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You successfully requested a reset of the server\"}]" - echo "info: The player ${player} requested a reset and has permission - server will reset" >> ${screenlog} - ./reset.sh --immediately + if cat "ops.json" | grep -q "${player}"; then + Log "info" "the player ${player} requested a reset and has permission - server will reset" "${screenLog}" + TellrawPlayer "${player}" "info: you successfully requested a reset of the server" + ./reset.sh --quiet --now exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to reset the server\"}]" - echo "warning: The player ${player} requested a reset and does not have permission to do so" >> ${screenlog} + Log "warn" "the player ${player} requested a reset and does not have permission to do so" "${screenLog}" + TellrawPlayer "${player}" "warn: you do not have permissions to reset the server" fi fi # check for perform reset string - if tail -1 "${screenlog}" | grep -q "perform reset"; then + if tail -1 "${screenLog}" | grep -q "perform reset"; then player=$(tail -1 screen.log | grep -oP '.*?(?=perform reset)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') - if cat ops.json | grep -q "${player}"; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You successfully requested a reset of the server\"}]" - echo "info: The player ${player} requested a reset and has permission - server will reset" >> ${screenlog} - ./reset.sh + if cat "ops.json" | grep -q "${player}"; then + Log "info" "the player ${player} requested a reset and has permission - server will reset" "${screenLog}" + TellrawPlayer "${player}" "info: you successfully requested a reset of the server" + ./reset.sh --quiet exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to reset the server\"}]" - echo "warning: The player ${player} requested a reset and does not have permission to do so" >> ${screenlog} + Log "warn" "the player ${player} requested a reset and does not have permission to do so" "${screenLog}" + TellrawPlayer "${player}" "warn: you do not have permissions to reset the server" fi fi } - - -# prints game over as pixel art on terminal -function PrintGameOver { - echo "${red} ______ _____ ${nocolor}" - echo "${red} / _____) / ___ \ ${nocolor}" - echo "${red} | / ___ ____ ____ ____ | | | |_ _ ____ ____ ${nocolor}" - echo "${red} | | (___)/ _ | \ / _ ) | | | | | | / _ )/ ___) ${nocolor}" - echo "${red} | \____/( ( | | | | ( (/ / | |___| |\ V ( (/ /| | ${nocolor}" - echo "${red} \_____/ \_||_|_|_|_|\____) \_____/ \_/ \____)_| ${nocolor}" - echo "${red} ${nocolor}" -} diff --git a/server.properties b/server.properties index 04fac64..ee50de5 100644 --- a/server.properties +++ b/server.properties @@ -1,52 +1,50 @@ #Minecraft server properties -#Fri Apr 16 21:02:13 CEST 2021 -spawn-protection=16 -max-tick-time=60000 -query.port=25565 -generator-settings= -sync-chunk-writes=true -force-gamemode=false -allow-nether=true -enforce-whitelist=false +#(timestamp of first initializing) +enable-jmx-monitoring=false +rcon.port=25575 gamemode=survival -broadcast-console-to-ops=true +enable-command-block=false enable-query=false -player-idle-timeout=0 -text-filtering-config= -difficulty=easy -spawn-monsters=true -broadcast-rcon-to-ops=true -op-permission-level=4 +level-name=world +motd=A Minecraft Server +query.port=25565 pvp=true -entity-broadcast-range-percentage=100 -snooper-enabled=true -level-type=default -hardcore=false -enable-status=true -enable-command-block=false -max-players=20 +difficulty=easy network-compression-threshold=256 -resource-pack-sha1= -max-world-size=29999984 -function-permission-level=2 -rcon.port=25575 -server-port=25565 -server-ip= -spawn-npcs=true +require-resource-pack=false +max-tick-time=60000 +use-native-transport=true +max-players=20 +online-mode=true +enable-status=true allow-flight=false -level-name=world +broadcast-rcon-to-ops=true view-distance=10 +server-ip= +resource-pack-prompt= +allow-nether=true +server-port=25565 +enable-rcon=false +sync-chunk-writes=true +op-permission-level=4 +prevent-proxy-connections=false resource-pack= -spawn-animals=true -white-list=false +entity-broadcast-range-percentage=100 +simulation-distance=10 rcon.password= -generate-structures=true -max-build-height=256 -online-mode=true -level-seed= -use-native-transport=true -prevent-proxy-connections=false -enable-jmx-monitoring=false -enable-rcon=false +player-idle-timeout=0 +force-gamemode=false rate-limit=0 -motd=A Minecraft Server +hardcore=false +white-list=false +broadcast-console-to-ops=true +spawn-npcs=true +spawn-animals=true +snooper-enabled=true +function-permission-level=2 +text-filtering-config= +spawn-monsters=true +enforce-whitelist=false +resource-pack-sha1= +spawn-protection=16 +max-world-size=29999984 diff --git a/server.settings b/server.settings index 9161aa4..d1b7cbe 100644 --- a/server.settings +++ b/server.settings @@ -4,98 +4,86 @@ # this file stores all the variables for the server. # if you know what you are doing, feel free to tinker with them ;^) -# command line colours -black="$(tput setaf 0)" # defines command line color black -red="$(tput setaf 1)" # defines command line color red -green="$(tput setaf 2)" # defines command line color green -yellow="$(tput setaf 3)" # defines command line color yellow -blue="$(tput setaf 4)" # defines command line color blue -magenta="$(tput setaf 5)" # defines command line color magenta -cyan="$(tput setaf 6)" # defines command line color cyan -white="$(tput setaf 7)" # defines command line color white -nocolor="$(tput sgr0)" # defines command line color nocolor - -# backup stuff -newhourly=$(date +"%H:00") # defines file format for new hourly backup -oldhourly=$(date -d "-23 hours" +"%H:00") # defines file format for old hourly backup -newdaily=$(date +"%Y-%m-%d") # defines file format for new daily backup -olddaily=$(date -d "-32 days" +"%Y-%m-%d") # defines file format for old daily backup -newweekly=$(date +"week-%U") # defines file format for new weekly backup -oldweekly=$(date -d "-12 weeks" +"week-%U") # defines file format for old weekly backup -newmonthly=$(date +"%B") # defines file format for new monthly backup -oldmonthly=$(date -d "-6 months" +"%B") # defines file format for old monthly backup +# github branch from whom scripts will fetch +branch="replaceBranch" + +# your contact info for players +adminContact="your admin did not edit the server settings file /:" + +# welcome messages if a player joins +welcome=("welcome on my server" "a warm welcome to" "greetings" "hello to" "welcome aboard" "make yourself at home" "have a nice time" "enjoy yourself") + +# arguments for java server +javaArgs="-Xms2G -Xmx2G -XX:ParallelGCThreads=2" + +# server resource paths +serverName="replaceServerName" +homeDirectory="replaceHomeDirectory" +serverDirectory="replaceServerDirectory" +backupDirectory="replaceBackupDirectory" +executableServerFile="replaceExecutableServerFile" + +# network public and private addresses +public="1.1.1.1" +private="192.168.1.1" + +# logfile names +screenLog="screen.log" +backupLog="backup.log" +debugLog="debug.log" # backup config -dohourly="true" # backup script will do backups hourly if set to true -dodaily="true" # backup script will do backups daily if set to true -doweekly="false" # backup script will do backups weekly if set to true -domonthly="false" # backup script will do backups monthly if set to true - -# backup events -hours=$(date +"%H") -weekday=$(date +"%u") -dayofmonth=$(date +"%d") -dailybackuptime="22" # defines hour for daily backups -weeklybackupday="7" # defines day of week for weekly backups -monthlybackupday="1" # defines day of month for monthly backups - -# world size stuff -absoluteworldsize=$(du -sb world | cut -f1) # assings value in bytes of world directory -absolutebackupsize=$(du -sb backups | cut -f1) # assings value in bytes of backup directory -absolutediskspace=$(df -B 1 / | tail -1 | awk '{print $4}') # assings value in bytes for free disk space -worldsize=$(du -sh world | cut -f1) # assigns human readable value of world directory -backupsize=$(du -sh backups | cut -f1) # assigns human readable value of backup directory -diskspace=$(df -h / | tail -1 | awk '{print $4}') # assigns human readable value of free disk space - -# warning and exiting parameters -diskspacepadding="2097152" # value in bytes for diskspace padding -diskspacewarning="8208608" # value in bytes for diskspace warning - -# logfiles -screenlog="screen.log" # defines name of screenlog file -backuplog="backup.log" # defines name of backuplog file -debuglog="debug.log" # defines name of debuglog file - -# binarys -java="/usr/bin/java" # defines path to java binary -screen="/usr/bin/screen" # defines path to screen binary - -# enables admins to perform cetrain actions with the ingame chat -enablesafetybackupstring="true" # enables safety backup string to perform a safety backup if set to true -enableconfirmrestartstring="true" # enables confirm restart string to perform a restart if set to true -enableconfirmupdatestring="false" # enables confirm update string to perform an update if set to true -enableconfirmresetstring="false" # enables confirm reset string to perform a reset if set to true - -# github branch -branch="main" # all scripts will fetch from this branch - -# enables debug logging -enabledebug="false" # enables debug log into logfiles if set to true - -# script time logging -date=$(date +"%Y-%m-%d %H:%M:%S") # defines format of script time logging - -# change to server console after startup -changetoconsole="replacechangetoconsole" # changes to server console after startup if set to true -# enables watchdog integrity checks for backups -enablewatchdog="replaceenablewatchdog" # executes watchdog script if set to true -# print welcome messages if a player joins -welcomemessage="replacewelcomemessage" # executes welcome script if set to true -# enables task execution if an admin uses ingame chat -enabletasks="replaceenabletasksmessage" # give admins the power of restarting your server - -# network stuff -dnsserver="replacednsserver" # server will ping it for public avalability checks -interface="replaceinterface" # server will ping it for private avalability checks - -# memory and threads -mems="replacemems" # minimun memory for java server process -memx="replacememx" # maximum memory for java server process -threadcount="replacethreadcount" # amount of threads which can be used by java server - -# files and directories -servername="replaceservername" # defines server name -homedirectory="replacehomedirectory" # defines path to home directory -serverdirectory="replaceserverdirectory" # defines path to server directory -backupdirectory="replacebackupdirectory" # defines path to backup directory -serverfile="replaceserverfile" # defines path to executable server file +doHourly=true +doDaily=true +doWeekly=false +doMonthly=false + +# values in bytes for disk space control +diskSpaceError=2097152 +diskSpaceWarning=8208608 + +# values in percent for backup size control +backupSizeError=200 +backupSizeWarning=400 + +# backup file formats +newHourly=$(date +"%H:00") +newDaily=$(date +"%Y-%m-%d") +newWeekly=$(date +"week-%U") +newMonthly=$(date +"%B" | awk '{print tolower($0)}') +oldHourly=$(date -d "-23 hours" +"%H:00") +oldDaily=$(date -d "-17 days" +"%Y-%m-%d") +oldWeekly=$(date -d "-11 weeks" +"week-%U") +oldMonthly=$(date -d "-5 months" +"%B" | awk '{print tolower($0)}') + +# world and backup sizes in bytes and human readable +worldSizeBytes=$(du -sb world | cut -f1) +backupSizeBytes=$(du -sb backups | cut -f1) +diskSpaceBytes=$(df -B 1 / | tail -1 | awk '{print $4}') +worldSizeHuman=$(du -sh world | cut -f1) +backupSizeHuman=$(du -sh backups | cut -f1) +diskSpaceHuman=$(df -h / | tail -1 | awk '{print $4}') + +# enable admin tasks from ingame chat +enablePerformBackup=true +enablePerformRestart=true +enablePerformUpdate=false +enablePerformReset=false + +# enables or disable some advanced options +enableDebug=false +changeToConsole=false +enableWelcomeMessage=true +enableBackupsWatchdog=true +enableAutoStartOnCrash=false + +# terminal output colours +black="$(tput setaf 0)" +red="$(tput setaf 1)" +green="$(tput setaf 2)" +yellow="$(tput setaf 3)" +blue="$(tput setaf 4)" +magenta="$(tput setaf 5)" +cyan="$(tput setaf 6)" +white="$(tput setaf 7)" +noColor="$(tput sgr0)" diff --git a/setup.sh b/setup.sh index b93a857..467fbe6 100644 --- a/setup.sh +++ b/setup.sh @@ -8,7 +8,7 @@ TERM="xterm" # branch selection from for github -branch="main" +branch="dev" # command line colours black="$(tput setaf 0)" @@ -19,935 +19,348 @@ blue="$(tput setaf 4)" magenta="$(tput setaf 5)" cyan="$(tput setaf 6)" white="$(tput setaf 7)" -nocolor="$(tput sgr0)" - -# parse script arguments -immediately=false -quiet=false -verbose=false -while [[ $# -gt 0 ]]; do - case "$1" in - -i) - immediately=true - ;; - -q) - quiet=true - ;; - -v) - verbose=true - ;; - --immediately) - immediately=true - ;; - --quiet) - quiet=true - ;; - --verbose) - verbose=true - ;; - *) - echo "bad argument: $1" - exit 1 - ;; - esac - shift -done +noColor="$(tput sgr0)" -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi +# prints all input to terminal at given log level +function Print { + if [[ ${1} == "ok" ]]; then + echo "$(date +"%H:%M:%S") ${green}ok${noColor}: ${2}" + fi + if [[ ${1} == "info" ]]; then + echo "$(date +"%H:%M:%S") ${blue}info${noColor}: ${2}" + fi + if [[ ${1} == "warn" ]]; then + echo "$(date +"%H:%M:%S") ${yellow}warn${noColor}: ${2}" + fi + if [[ ${1} == "error" ]]; then + echo "$(date +"%H:%M:%S") ${red}error${noColor}: ${2}" + fi + if [[ ${1} == "fatal" ]]; then + echo "$(date +"%H:%M:%S") ${red}fatal${noColor}: ${2}" + fi + if [[ ${1} == "action" ]]; then + echo "$(date +"%H:%M:%S") ${cyan}action${noColor}: ${2}" + fi +} + +# function for storing variables in server.settings +function StoreSettings { + sed -i "s|${1}|${2}|g" server.settings +} + +# function for storing settings in server.properties +function StoreProperties { + sed -i "s|${1}|${2}|g" server.properties +} + +# store to crontab function +function StoreCrontab { + crontab -l | { + cat + echo "${1}" + } | crontab - +} -# check for operating system compatibility and for free memory -if [ "$(uname)" == "Darwin" ]; then - # inform user about macOS - echo "$(tput bold)$(tput setaf 3)warning: you are running macOS as your operating system - your server may not run!$(tput sgr0)" - # get free memory on macOS - memory=$(($(vm_stat | head -2 | tail -1 | awk '{print $3}' | sed 's/.$//') + $(vm_stat | head -4 | tail -1 | awk '{print $3}' | sed 's/.$//') * 4096)) - # check memory - if (( ${memory} < 2560000000 )); then - echo "$(tput bold)$(tput setaf 3)warning: your system has less than 2.56 GB of memory - this may impact server performance!$(tput sgr0)" +# check for Linux +function CheckLinux { + if [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then + # inform user about Linux + Print "ok" "you are running Linux as your operating system - your server will likely run!" + # get free memory on linux + memory="$(free -b | tail -2 | head -1 | awk '{print $4}')" + # check memory + if ((${memory} < 2560000000)); then + Print "warn" "your system has less than 2.56 GB of memory - this may impact server performance!" + fi + # get number of threads on Linux + threads=$(nproc) + # check threads + if ((${threads} < 4)); then + Print "warn" "your system has less than 4 threads - this may impact server performance!" + fi + supported=true + else + supported=false fi - # get number of threads on macOS - threads=$(nproc) - # check threads - if (( ${threads} < 4 )); then - echo "$(tput bold)$(tput setaf 3)warning: your system has less than 4 threads - this may impact server performance!$(tput sgr0)" +} + +# check for macOS +function CheckMacOS { + if [ "$(uname)" == "Darwin" ]; then + # inform user about macOS + Print "warn" "you are running macOS as your operating system - your server may not run!" + # get free memory on macOS + memory=$(($(vm_stat | head -2 | tail -1 | awk '{print $3}' | sed 's/.$//') + $(vm_stat | head -4 | tail -1 | awk '{print $3}' | sed 's/.$//') * 4096)) + # check memory + if ((${memory} < 2560000000)); then + Print "warn" "your system has less than 2.56 GB of memory - this may impact server performance!" + fi + # get number of threads on macOS + threads=$(nproc) + # check threads + if ((${threads} < 4)); then + Print "warn" "your system has less than 4 threads - this may impact server performance!" + fi + supported=true + else + supported=false fi -elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then - # get free memory on linux - memory="$(free -b | tail -2 | head -1 | awk '{print $4}')" - # check memory - if (( ${memory} < 2560000000 )); then - echo "$(tput bold)$(tput setaf 3)warning: your system has less than 2.56 GB of memory - this may impact server performance!$(tput sgr0)" +} + +# check for Windows +function CheckWindows { + if [ "$(expr substr $(uname -s) 1 10)" == "MINGW64_NT" ]; then + # inform user about Windows + Print "fatal" "you are running Windows as your operating system - your server will not run!" + supported=false + exit 1 fi - # get number of threads on Linux - threads=$(nproc) - # check threads - if (( ${threads} < 4 )); then - echo "$(tput bold)$(tput setaf 3)warning: your system has less than 4 threads - this may impact server performance!$(tput sgr0)" +} + +# check for unsupported OS +function CheckUnsupported { + if [ supported == false ]; then + # inform user about unsupported operating system + Print "fatal" "you are running an unsupported operating system - your server will not run!" + exit 1 fi -elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW64_NT" ]; then - # inform user about Windows - echo "$(tput bold)$(tput setaf 1)fatal: you are running Windows as your operating system - your server will not run!$(tput sgr0)" - exit 1 -else - # inform user about unsupported operating system - echo "$(tput bold)$(tput setaf 1)fatal: you are running an unsupported operating system - your server will not run!$(tput sgr0)" - exit 1 -fi +} -# check if every required package is installed -# declare all packages in an array -declare -a packages=( "apt" "java" "screen" "date" "tar" "echo" "ping" "grep" "wget" "man" "crontab" "nano" "less" "sed" "pv" "awk" ) -# get length of package array -packageslength=${#packages[@]} -# use for loop to read all values and indexes -for (( i = 1; i < ${packageslength} + 1; i ++ )); do - if ! command -v ${packages[$i-1]} &> /dev/null; then - echo "${red}fatal: the package ${packages[${i}-1]} is not installed on your system" +# function for downloading server file from mojang api with error checking +function FetchServerFile { + Print "info" "downloading minecraft-server.${version}.jar..." + wget -q -O "minecraft-server.${version}.jar" "https://launcher.mojang.com/v1/objects/${1}/server.jar" + executableServerFile="${serverDirectory}/minecraft-server.${version}.jar" + if [[ -s "minecraft-server.${version}.jar" ]]; then + Print "ok" "download successful" + else + Print "fatal" "downloaded server-file minecraft-server.${version}.jar is empty or not available" + fi +} + +# root safety check +function RootSafety { + if [ $(id -u) = 0 ]; then + Print "fatal" "please do not run me as root :( - this is dangerous!" exit 1 fi -done +} + +# checks if a script is already running +function ScriptSafety { + if [[ ${force} == false ]]; then + if pidof -x "setup.sh" &>/dev/null; then + Print "warn" "script setup.sh is already running" + exit 1 + fi + fi +} + +# safety +RootSafety +ScriptSafety + +# os detection +CheckLinux +CheckMacOS +CheckWindows +CheckUnsupported # user info about script -echo "${cyan}I will setup a minecraft server for you${nocolor} ${blue};^)${nocolor}" +Print "action" "i will setup a minecraft server for you ;^)" # initial question -echo "How should I call your server?" -echo "Please enter a servername: Example: ${yellow}minecraft${nocolor}" -read -re -i "minecraft" -p "Your name: " servername +read -re -i "minecraft" -p "$(date +"%H:%M:%S") prompt: how should I call your server? your name: " serverName regex="^[a-zA-Z0-9]+$" verify="false" -while [[ ${verify} == "false" ]]; do - if [[ ! ${servername} =~ ${regex} ]]; then - read -p "Please enter a servername which only contains letters and numbers: " servername +while [[ ${verify} == false ]]; do + if [[ ! "${serverName}" =~ ${regex} ]]; then + read -p "$(date +"%H:%M:%S") prompt: please enter a name which only contains letters and numbers: " serverName else - check1="true" + regexCheck=true fi - if [ -d ${servername} ]; then - read -p "Directory ${servername} already exists - please enter another directory: " servername + if [ -d "${serverName}" ]; then + read -p "$(date +"%H:%M:%S") prompt: directory ${serverName} already exists - please enter another directory: " serverName else - check2="true" + existsCheck=true fi - if [[ ${check1} == "true" ]] && [[ ${check2} == "true" ]]; then + if [[ ${regexCheck} == true ]] && [[ ${existsCheck} == true ]]; then verify=true else - verify="false" + verify=false fi done -echo "Your Server will be called ${green}${servername}${nocolor}" + +# user info +Print "info" "your server will be called ${green}${serverName}${noColor}" # store homedirectory -homedirectory=`pwd` +homeDirectory=$(pwd) # ask for permission to proceed -echo "I will download the following:" -echo "start, stop, restart, backup and many more scripts from GitHub." -read -p "Continue? [Y/N]: " +Print "info" "i will download start, stop, restart, backup and many more scripts from github" +read -p "$(date +"%H:%M:%S") prompt: proceed? (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY + read -p "$(date +"%H:%M:%S") prompt: please press y or n: " REPLY done -if [[ $REPLY =~ ^[Yy]$ ]] - then echo "${green}starting setup...${nocolor}" - else echo "${red}exiting...${nocolor}" - exit 1 +if [[ $REPLY =~ ^[Yy]$ ]]; then + Print "ok" "starting setup..." +else + Print "error" "exiting..." + exit 1 fi -# set up directorys -echo "I will now setup a server and backup directory." - # set up server directory -echo -n "info: setting up a serverdirectory... " -mkdir ${servername} -cd ${servername} -echo "done" - -# check if verbose mode is on -function CheckVerbose { - if [[ ${verbose} == true ]]; then - echo "${1}" - fi -} - -# check if quiet mode is on -function CheckQuiet { - if ! [[ ${quiet} == true ]]; then - echo "${1}" - fi -} - -# function for fetching scripts from github with error checking -function FetchScriptFromGitHub { - wget --spider --quiet https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${1} - if [ "$?" != 0 ]; then - echo "${red}Fatal: Unable to connect to GitHub API. Script will exit! (maybe chose another branch?)${nocolor}" - exit 1 - else - CheckVerbose "Fetching file: ${1} from branch ${branch} on GitHub..." - wget -q -O ${1} https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${1} - fi -} +Print "info" "setting up a serverdirectory..." +mkdir "${serverName}" +cd "${serverName}" # user info about download -echo "info: downloading scripts from GitHub... " +Print "info" "downloading scripts from github..." # downloading scripts from github -# declare all scripts in an array -declare -a scripts1=( "LICENSE" "README.md" "server.settings" "server.properties" "server.functions" "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "maintenance.sh" "prerender.sh" "watchdog.sh" "welcome.sh" "worker.sh" "vent.sh" ) -# get length of script array -scriptslength=${#scripts1[@]} -# loop through all entries in the array -for (( i = 1; i < ${scriptslength} + 1; i ++ )); do - FetchScriptFromGitHub "${scripts1[${i}-1]}" +declare -a scriptsDownload=("server.settings" "server.properties" "server.functions" "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "worker.sh" "vent.sh") +arrayLength=${#scriptsDownload[@]} +for ((i = 0; i < ${arrayLength}; i++)); do + wget -q -O "${scriptsDownload[${i}]}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${scriptsDownload[${i}]}" done +# user info about download +Print "ok" "download successful" + # make selected scripts executable -# declare all scripts in an array -declare -a scripts2=( "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "maintenance.sh" "prerender.sh" "watchdog.sh" "welcome.sh" "worker.sh" "vent.sh" ) -# get length of script array -scriptslength=${#scripts2[@]} -# loop through all entries in the array -for (( i = 1; i < ${scriptslength} + 1; i ++ )); do - CheckVerbose "Setting script ${scripts2[${i}-1]} executable" - chmod +x ${scripts2[${i}-1]} +declare -a scriptsExecutable=("start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "worker.sh" "vent.sh") +arrayLength=${#scriptsExecutable[@]} +for ((i = 0; i < ${arrayLength}; i++)); do + chmod +x "${scriptsExecutable[${i}]}" done # store serverdirectory -serverdirectory=`pwd` - -echo "${green}ok: download successful${nocolor}" - -# function for downloading serverfile from mojang api with error checking -function FetchServerFileFromMojan { - echo -n "downloading minecraft-server.${version}.jar... " - wget -q -O minecraft-server.${version}.jar https://launcher.mojang.com/v1/objects/${1}/server.jar - serverfile="${serverdirectory}/minecraft-server.${version}.jar" - echo "${green}done${nocolor}" - if ! [[ -s "minecraft-server.${version}.jar" ]]; then - echo "download error: downloaded server-file minecraft-server.${version}.jar is empty or not available" - fi -} +serverDirectory=$(pwd) -# download java executable from mojang.com -PS3="Which server version would you like to install? " -versions=("1.17.1" "1.16.5" "1.16.4" "1.16.3") +# download java executable from mojang +PS3="$(date +"%H:%M:%S") prompt: which server version would you like to install? " +versions=("1.18.1" "1.17.1" "1.16.5") select version in "${versions[@]}"; do case ${version} in - "1.17.1") - FetchServerFileFromMojan "a16d67e5807f57fc4e550299cf20226194497dc2" - break - ;; - "1.16.5") - FetchServerFileFromMojan "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" - break - ;; - "1.16.4") - FetchServerFileFromMojan "35139deedbd5182953cf1caa23835da59ca3d7cd" - break + "1.18.1") + FetchServerFile "125e5adf40c659fd3bce3e66e67a16bb49ecc1b9" + break + ;; + "1.17.1") + FetchServerFile "a16d67e5807f57fc4e550299cf20226194497dc2" + break + ;; + "1.16.5") + FetchServerFile "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" + break ;; - "1.16.3") - FetchServerFileFromMojan "f02f4473dbf152c23d7d484952121db0b36698cb" - break + *) + echo "please choose an option from the list: " ;; - *) echo "Please choose an option from the list: ";; esac done # user information about execute at start -echo "Your Server will execute ${green}${serverfile}${nocolor} at start" +Print "info" "your server will execute ${executableServerFile} at start" # set up backupdirectory with child directories -echo -n "info: setting up a backupdirectory... " +Print "info" "setting up a backupdirectory..." mkdir world mkdir backups - cd backups - CheckVerbose "creating ${serverdirectory}/backups/hourly" - mkdir hourly - CheckVerbose "creating ${serverdirectory}/backups/daily" - mkdir daily - CheckVerbose "creating ${serverdirectory}/backups/weekly" - mkdir weekly - CheckVerbose "creating ${serverdirectory}/backups/monthly" - mkdir monthly - CheckVerbose "creating ${serverdirectory}/backups/cached" - mkdir cached - backupdirectory=`pwd` - cd ${serverdirectory} -echo "done" - -# ask all the importatnt user input -echo "${cyan}auto setup means you are asked fewer questions but there will not be as much customisation for you${nocolor}" -echo "${cyan}nerdy setup means you are able to customise everything - you are able to change these settings later${nocolor}" -PS3="How would you like to setup your server? " -serversetup=("auto" "nerdy") -select setup in ${serversetup[@]}; do - case ${setup} in - "auto") - # set nerdysetup to false - nerdysetup=false - break - ;; - "nerdy") - # set nerdysetup to true - nerdysetup=true - break - ;; - *) - echo "Please chose an option from the list: " - ;; - esac +cd backups +declare -a backupChildren=("hourly" "daily" "weekly" "monthly" "cached") +arrayLength=${#backupChildren[@]} +for ((i = 0; i < ${arrayLength}; i++)); do + mkdir "${backupChildren[${i}]}" done - -# check if nerdysetup is true -if [[ ${nerdysetup} == true ]]; then - - # ask for a valid dnsserver - echo "Please tell me which dnsserver you would like to use. Example: ${yellow}1.1.1.1${nocolor}" - read -re -i "1.1.1.1" -p "Your dnsserver: " dnsserver - regex="^(0*(1?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))\.){3}" - while [[ ! ${dnsserver} =~ ${regex} ]]; do - read -p "Please enter a valid ip address: " dnsserver - done - echo "Your server will ping ${green}${dnsserver}${nocolor} at start." - - # ask for a valid interface - echo "Please tell me which interface you would like to use. Example: ${yellow}192.168.1.1${nocolor}" - read -re -i "192.168.1.1" -p "Your interface: " interface - regex="^(0*(1?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))\.){3}" - while [[ ! ${interface} =~ ${regex} ]]; do - read -p "Please enter a valid ip address: " interface - done - echo "Your server will ping ${green}${interface}${nocolor} at start." - - # ask for minimum memory - echo "How much minimum memory would you like to grant your Server? Example: ${yellow}256${nocolor}" - read -re -i "256" -p "Your amount: " mems - regex="^([2-9][5-9][6-9]|[1-4][0-9][0-9][0-9])$" - while [[ ! ${mems} =~ ${regex} ]]; do - read -p "Please enter a number between 256 and 4096: " mems - done - echo "Your Server will will have ${green}${mems}${nocolor} MB of minimum memory allocated." - mems="-Xms${mems}M" - - # ask for maximum memory - echo "How much maximum memory would you like to grant your Server? Example: ${yellow}2048${nocolor}" - read -re -i "2048" -p "Your amount: " memx - regex="^([2-9][0-9][4-9][8-9]|[0-3][0-2][0-7][0-6][0-8])$" - while [[ ! ${memx} =~ ${regex} ]]; do - read -p "Please enter a number between 2048 and 32768: " memx - done - echo "Your Server will will have ${green}${memx}${nocolor} MB of maximum memory allocated." - memx="-Xms${memx}M" - - # ask for amount of threads - echo "How many threads would you like your Server to use? Example: ${yellow}2${nocolor}" - read -re -i "2" -p "Your amount: " threadcount - regex="^(0?[1-9]|[1-2][0-9]|3[0-2])$" - while [[ ! ${threadcount} =~ ${regex} ]]; do - read -p "Please enter a number between 1 and 32: " threadcount - done - echo "Your Server will will have ${green}${threadcount}${nocolor} threads to work with." - threadcount="-XX:ParallelGCThreads=${threadcount}" - - # ask for view distance - echo "Please specify your desired view-distance. Example: ${yellow}16${nocolor}" - read -re -i "16" -p "Your view-distance: " viewdistance - regex="^([2-9]|[1-5][0-9]|6[0-4])$" - while [[ ! ${viewdistance} =~ ${regex} ]]; do - read -p "Please enter a number between 2 and 64: " viewdistance - done - echo "Your Server will have ${green}${viewdistance}${nocolor} chunks view-distance." - viewdistance="view-distance=${viewdistance}" - - # ask for spawn protection - echo "Please specify your desired spawn-protection. Example: ${yellow}16${nocolor}" - read -re -i "16" -p "Your spawn-protection: " spawnprotection - regex="^([2-9]|[1-5][0-9]|6[0-4])$" - while [[ ! ${spawnprotection} =~ ${regex} ]]; do - read -p "Please enter a number between 2 and 64: " spawnprotection - done - echo "Your Server will have ${green}${spawnprotection}${nocolor} blocks spawn-protection." - spawnprotection="spawn-protection=${spawnprotection}" - - # ask for max player count - echo "Please tell me the max-players amount. Example: ${yellow}8${nocolor}" - read -re -i "8" -p "Your max-players: " maxplayers - regex="^([2-9]|[0-9][0-9]|1[0-9][0-9]|200)$" - while [[ ! ${maxplayers} =~ ${regex} ]]; do - read -p "Please enter a number between 2 and 200: " maxplayers - done - echo "Your Server will have ${green}${maxplayers}${nocolor} max-players." - maxplayers="max-players=${maxplayers}" - - # ask for server port - echo "Please specify your desired server-port. Example: ${yellow}25565${nocolor}" - read -re -i "25565" -p "Your server-port: " serverport - regex="^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$" - while [[ ! ${serverport} =~ ${regex} ]]; do - read -p "Please enter a valid port between 0 and 65535: " serverport - done - echo "Your Server will be on ${green}${serverport}${nocolor}" - serverport="server-port=${serverport}" - - # ask for query port - echo "Please specify your desired query-port. Example: ${yellow}25565${nocolor}" - read -re -i "25565" -p "Your query-port: " queryport - regex="^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$" - while [[ ! ${queryport} =~ ^${regex} ]]; do - read -p "Please enter a valid port between 0 and 65535: " queryport - done - echo "Your Server will be on ${green}${queryport}${nocolor}" - queryport="query.port=${queryport}" - - # ask for query - echo "Would you like your server have a query? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " enablequery - regex="^(true|false)$" - while [[ ! ${enablequery} =~ ${regex} ]]; do - read -p "Please enter true or false: " enablequery - done - echo "Your Server will be on ${green}${enablequery}${nocolor}" - enablequery="enably-query=${enablequery}" - - # ask for gamemode - echo "Which gamemode would you like to play? Example: ${yellow}survival${nocolor}" - read -re -i "survival" -p "Your gamemode: " gamemode - regex="^(survival|creative|adventure|spectator)$" - while [[ ! ${gamemode} =~ ${regex} ]]; do - read -p "Please enter a valid gamemode: " gamemode - done - echo "Your Server will be on ${green}${gamemode}${nocolor}" - gamemode="gamemode=${gamemode}" - - # ask for forced gamemode - echo "Would like like to force the gamemode on your server? ${yellow}false${nocolor}" - read -re -i "false" -p "Your choice: " forcegamemode - regex="^(true|false)$" - while [[ ! ${forcegamemode} =~ ${regex} ]]; do - read -p "Please enter true or false: " forcegamemode - done - echo "Your Server will be on ${green}${forcegamemode}${nocolor}" - forcegamemode="force-gamemode=${forcegamemode}" - - # ask for difficulty - echo "Which difficulty would you like to have? Example: ${yellow}normal${nocolor}" - read -re -i "normal" -p "Your difficulty: " difficulty - regex="^(peaceful|easy|normal|hard)$" - while [[ ! ${difficulty} =~ ${regex} ]]; do - read -p "Please enter a valid difficulty: " difficulty - done - echo "Your Server will be on ${green}${difficulty}${nocolor}" - difficulty="difficulty=${difficulty}" - - # ask for hardcore mode - echo "Would you like to turn on hardcore mode? Example: ${yellow}false${nocolor}" - read -re -i "false" -p "Your choice: " hardcore - regex="^(true|false)$" - while [[ ! ${hardcore} =~ ${regex} ]]; do - read -p "Please enter true or false: " hardcore - done - echo "Your Server will be on ${green}${hardcore}${nocolor}" - hardcore="hardcore=${hardcore}" - - # ask for monsters - echo "Would you like your server to spawn monsters? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " monsters - regex="^(true|false)$" - while [[ ! ${monsters} =~ ${regex} ]]; do - read -p "Please enter true or false: " monsters - done - echo "Your Server will be on monsters ${green}${monsters}${nocolor}" - monsters="spawn-monsters=${monsters}" - - # ask for whitelist - echo "Would you like to turn on the whitelist? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " whitelist - regex="^(true|false)$" - while [[ ! ${whitelist} =~ ${regex} ]]; do - read -p "Please enter true or false: " whitelist - done - echo "Your Server will be on whitelist ${green}${whitelist}${nocolor}" - whitelist="white-list=${whitelist}" - - # ask for enforced whitelist - echo "Would you like to enforce the whitelist on your server? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " enforcewhitelist - regex="^(true|false)$" - while [[ ! ${enforcewhitelist} =~ ${regex} ]]; do - read -p "Please enter true or false: " enforcewhitelist - done - echo "Your Server will be on enforcewhitelist ${green}${enforcewhitelist}${nocolor}" - enforcewhitelist="enforce-whitelist=${enforcewhitelist}" - - # ask for online mode - echo "Would you like to run your server in online mode? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " onlinemode - regex="^(true|false)$" - while [[ ! ${onlinemode} =~ ${regex} ]]; do - read -p "Please enter true or false: " onlinemode - done - echo "Your Server will be on onlinemode ${green}${onlinemode}${nocolor}" - onlinemode="online-mode=${onlinemode}" - - # ask for pvp - echo "Would you like to turn on pvp? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " pvp - regex="^(true|false)$" - while [[ ! ${pvp} =~ ${regex} ]]; do - read -p "Please enter true or false: " pvp - done - echo "Your Server will be on pvp ${green}${pvp}${nocolor}" - pvp="pvp=${pvp}" - - # ask for animals - echo "Would you like to spawn animals on your server? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " animals - regex="^(true|false)$" - while [[ ! ${animals} =~ ${regex} ]]; do - read -p "Please enter true or false: " animals - done - echo "Your Server will be on animals ${green}${animals}${nocolor}" - animals="spawn-animals=${animals}" - - # ask for nether - echo "Would you like to activate the nether on your server? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " nether - regex="^(true|false)$" - while [[ ! ${nether} =~ ${regex} ]]; do - read -p "Please enter true or false: " nether - done - echo "Your Server will be on nether ${green}${nether}${nocolor}" - nether="allow-nether=${nether}" - - # ask for npcs - echo "Would you like to spawn npcs on your server? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " npcs - regex="^(true|false)$" - while [[ ! ${npcs} =~ ${regex} ]]; do - read -p "Please enter true or false: " npcs - done - echo "Your Server will be on npcs ${green}${npcs}${nocolor}" - npcs="spawn-npcs=${npcs}" - - # ask for structures - echo "Would you like your server to generate structures? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " structures - regex="^(true|false)$" - while [[ ! ${structures} =~ ${regex} ]]; do - read -p "Please enter true or false: " structures - done - echo "Your Server will be on structures ${green}${structures}${nocolor}" - structures="generate-structures=${structures}" - - # ask for command blocks - echo "Would you like to turn on command-blocks? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " cmdblock - regex="^(true|false)$" - while [[ ! ${cmdblock} =~ ${regex} ]]; do - read -p "Please enter true or false: " cmdblock - done - echo "Your Server will be on ${green}${cmdblock}${nocolor}" - cmdblock="enable-command-block=${cmdblock}" - - # ask for entity broadcast range - echo "How far would you like to be able to see entities? Example: ${yellow}100${nocolor}" - read -re -i "100" -p "Your range: " entitybroadcast - regex="^([1-4][0-9][0-9]|500)$" - while [[ ! ${entitybroadcast} =~ ${regex} ]]; do - read -p "Please enter a number between 100 and 500: " entitybroadcast - done - echo "Your Server will broadcast entities ${green}${entitybroadcast}${nocolor}" - entitybroadcast="entity-broadcast-range-percentage=${entitybroadcast}" - - # ask for enable watchdog - echo "Would you like to check the integrity of your backups? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " enablewatchdog - regex="^(true|false)$" - while [[ ! ${enablewatchdog} =~ ${regex} ]]; do - read -p "Please enter true or false: " enablewatchdog - done - echo "Your Server will be on enable-watchdog ${green}${enablewatchdog}${nocolor}" - - # ask for welcome message - echo "Would you like to print welcome messages if a player joins after successful startup? Example: ${yellow}true${nocolor}" - read -re -i "true" -p "Your choice: " welcomemessage - regex="^(true|false)$" - while [[ ! ${welcomemessage} =~ ${regex} ]]; do - read -p "Please enter true or false: " welcomemessage - done - echo "Your Server will be on welcome-message ${green}${welcomemessage}${nocolor}" - - # ask for server console - echo "Would you like to change to server console after successful startup? Example: ${yellow}false${nocolor}" - read -re -i "false" -p "Your choice: " changetoconsole - regex="^(true|false)$" - while [[ ! ${changetoconsole} =~ ${regex} ]]; do - read -p "Please enter true or false: " changetoconsole - done - echo "Your Server will be on change-to-console ${green}${changetoconsole}${nocolor}" - - # ask for admin task execution - echo "Would you like to enable admin tasks for the in game chat? Example: ${yellow}false${nocolor}" - read -re -i "false" -p "Your choice: " enabletasks - regex="^(true|false)$" - while [[ ! ${enabletasks} =~ ${regex} ]]; do - read -p "Please enter true or false: " enabletasks - done - echo "Your Server will be on admin-tasks ${green}${enabletasks}${nocolor}" - - # ask for server message - echo "Please chose your server message. Example: ${yellow}Hello World, I am your new Minecraft Server ;^)${nocolor}" - read -re -i "Hello World, I am your new Minecraft Server ;^)" -p "Your message: " motd - echo "Your server message will be: ${green}${motd}${nocolor}" - motd="motd=${motd}" - -fi - -# check if nerdysetup is false -if [[ ${nerdysetup} == false ]]; then - - # declare standart values - dnsserver="1.1.1.1" - interface="192.168.1.1" - mems="-Xms256M" - memx="-Xms2048M" - threadcount="-XX:ParallelGCThreads=2" - viewdistance="view-distance=16" - spawnprotection="spawn-protection=16" - maxplayers="max-players=8" - serverport="server-port=25565" - queryport="query.port=25565" - enablequery="enable-query=true" - gamemode="gamemode=survival" - forcegamemode="force-gamemode=false" - difficulty="difficulty=normal" - hardcore="hardcore=false" - monsters="spawn-monsters=true" - whitelist="white-list=true" - enforcewhitelist="enforce-whitelist=true" - onlinemode="online-mode=true" - pvp="pvp=true" - animals="spawn-animals=true" - nether="allow-nether=true" - npcs="spawn-npcs=true" - structures="generate-structures=true" - cmdblock="enable-command-block=true" - entitybroadcast="entity-broadcast-range-percentage=100" - enablewatchdog="true" - enabletasks="false" - welcomemessage="true" - changetoconsole="false" - motd="motd=Hello World, I am your new Minecraft Server ;^)" - -fi +backupDirectory=$(pwd) +cd ${serverDirectory} # eula question -echo "Would you like to accept the End User License Agreement from Mojang?" -echo "If you say no your server will not be able to run" -echo "${yellow}If you say yes you must abide by their terms and conditions!${nocolor}" -read -p "[Y/N]: " +Print "info" "would you like to accept the end user license agreement from mojang?" +read -p "$(date +"%H:%M:%S") prompt: (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY + read -p "$(date +"%H:%M:%S") prompt: please press y or n: " REPLY done -if [[ ${REPLY} =~ ^[Yy]$ ]] - then echo "${green}accepting eula...${nocolor}" - echo "eula=true" >> eula.txt - else echo "${red}declining eula...${nocolor}" - echo "eula=false" >> eula.txt -fi - -# function for storing variables in server.settings -function StoreToSettings { - sed -i "s|${1}|${2}|g" server.settings -} - -# function for storing settings in server.properties -function StoreToProperties { - sed -i "s|${1}|${2}|g" server.properties -} - -# store all the userinput -echo -n "storing variables in server.settings... " - StoreToSettings "replacechangetoconsole" "${changetoconsole}" - StoreToSettings "replaceenablewatchdog" "${enablewatchdog}" - StoreToSettings "replacewelcomemessage" "${welcomemessage}" - StoreToSettings "replaceenabletasksmessage" "${enabletasks}" - StoreToSettings "replacednsserver" "${dnsserver}" - StoreToSettings "replaceinterface" "${interface}" - StoreToSettings "replacemems" "${mems}" - StoreToSettings "replacememx" "${memx}" - StoreToSettings "replacethreadcount" "${threadcount}" - StoreToSettings "replaceservername" "${servername}" - StoreToSettings "replacehomedirectory" "${homedirectory}" - StoreToSettings "replaceserverdirectory" "${serverdirectory}" - StoreToSettings "replacebackupdirectory" "${backupdirectory}" - StoreToSettings "replaceserverfile" "${serverfile}" -echo "done" - -# store all the userinput -echo -n "storing variables in server.properties... " - StoreToProperties "white-list=false" "${whitelist}" - StoreToProperties "enforce-whitelist=false" "${enforcewhitelist}" - StoreToProperties "spawn-animals=true" "${animals}" - StoreToProperties "spawn-monsters=true" "${monsters}" - StoreToProperties "generate-structures=true" "${structures}" - StoreToProperties "spawn-npcs=true" "${npcs}" - StoreToProperties "allow-nether=true" "${nether}" - StoreToProperties "pvp=true" "${pvp}" - StoreToProperties "enable-command-block=false" "${cmdblock}" - StoreToProperties "gamemode=survival" "${gamemode}" - StoreToProperties "force-gamemode=false" "${forcegamemode}" - StoreToProperties "difficulty=easy" "${difficulty}" - StoreToProperties "hardcore=false" "${hardcore}" - StoreToProperties "max-players=20" "${maxplayers}" - StoreToProperties "view-distance=10" "${viewdistance}" - StoreToProperties "entity-broadcast-range-percentage=100" "${entitybroadcast}" - StoreToProperties "spawn-protection=16" "${spawnprotection}" - StoreToProperties "server-port=25565" "${serverport}" - StoreToProperties "query.port=25565" "${queryport}" - StoreToProperties "enable-query=false" "${enablequery}" - StoreToProperties "motd=A Minecraft Server" "${motd}" -echo "done" - -# create logfiles with welcome message -. ./server.settings -. ./server.functions -echo "Hello World, this ${servername}-server and log-file was created on ${date}" >> ${screenlog} -echo "Hello World, this ${servername}-server and log-file was created on ${date}" >> ${backuplog} -echo "" >> ${backuplog} -echo "" >> ${backuplog} - -# store to crontab function -function StoreToCrontab { - crontab -l | { cat; echo "${1}"; } | crontab - -} - -# check if nerdysetup is true -if [[ ${nerdysetup} == true ]]; then - - # write servername and date into crontab - date=$(date +"%Y-%m-%d %H:%M:%S") - StoreToCrontab "# Minecraft ${servername} server automatisation - executed setup.sh at ${date}" - - # crontab e-mail config - read -p "Would you like to receive emails from your crontab? [Y/N]: " - regex="^(Y|y|N|n)$" - while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY - done - if [[ ${REPLY} =~ [Yy]$ ]] - then read -p "Please enter your email address: " emailaddress - StoreToCrontab "MAILTO=${emailaddress}" - emailchoice=true - else echo "${yellow}no emails${nocolor}" - StoreToCrontab "#MAILTO=youremail@example.com" - emailchoice=false - fi - - # define colors for tput - StoreToCrontab "TERM=xterm" - StoreToCrontab "" - - # crontab automatization backups - read -p "Would you like to automate backups? [Y/N]: " - regex="^(Y|y|N|n)$" - while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY - done - if [[ ${REPLY} =~ ^[Yy]$ ]] - then echo "${green}automating backups...${nocolor}" - StoreToCrontab "# minecraft ${servername} server backup hourly at **:00" - StoreToCrontab "0 * * * * cd ${serverdirectory} && ./backup.sh --quiet" - backupchoice=true - else echo "${yellow}no automated backups${nocolor}" - StoreToCrontab "# minecraft ${servername} server backup hourly at **:00" - StoreToCrontab "#0 * * * * cd ${serverdirectory} && ./backup.sh --quiet" - backupchoice=false - fi - - # crontab automated start and stop - read -p "Would you like to start and stop your server at a certain time? [Y/N]: " - regex="^(Y|y|N|n)$" - while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY - done - if [[ ${REPLY} =~ ^[Yy]$ ]] - then echo "${green}automating start and stop...${nocolor}" - read -p "Your start time [0 - 23]: " starttime - read -p "Your stop time [0 - 23]: " stoptime - StoreToCrontab "# minecraft ${servername} server start at ${starttime}" - StoreToCrontab "0 ${starttime} * * * cd ${serverdirectory} && ./start.sh --quiet" - StoreToCrontab "# minecraft ${servername} server stop at ${stoptime}" - StoreToCrontab "0 ${stoptime} * * * cd ${serverdirectory} && ./stop.sh --quiet" - startstopchoice=true - else echo "${yellow}no automated start and stop${nocolor}" - StoreToCrontab "# minecraft ${servername} server start at 06:00" - StoreToCrontab "#0 6 * * * cd ${serverdirectory} && ./start.sh --quiet" - StoreToCrontab "# minecraft ${servername} server stop at 23:00" - StoreToCrontab "#0 23 * * * cd ${serverdirectory} && ./stop.sh --quiet" - startstopchoice=false - fi - - # crontab automatization restart - read -p "Would you like to restart your server at 12:00? [Y/N]: " - regex="^(Y|y|N|n)$" - while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY - done - if [[ ${REPLY} =~ ^[Yy]$ ]] - then echo "${green}automatic restarts at 02:00${nocolor}" - StoreToCrontab "# minecraft ${servername} server restart at 02:00 on Sundays" - StoreToCrontab "0 12 * * 0 cd ${serverdirectory} && ./restart.sh --quiet" - restartchoice=true - else echo "${yellow}no restarts${nocolor}" - StoreToCrontab "# minecraft ${servername} server restart at 02:00 on Sundays" - StoreToCrontab "#0 12 * * 0 cd ${serverdirectory} && ./restart.sh --quiet" - restartchoice=false - fi - - # crontab automatization updates - read -p "Would you like to update your server every Sunday at 18:00? [Y/N]: " - regex="^(Y|y|N|n)$" - while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY - done - if [[ ${REPLY} =~ ^[Yy]$ ]] - then echo "${green}automatic update at Sunday${nocolor}" - StoreToCrontab "# minecraft ${servername} server update at 18:00 on Sundays" - StoreToCrontab "0 18 * * 0 cd ${serverdirectory} && ./update.sh --quiet" - updatechoice=true - else echo "${yellow}no updates${nocolor}" - StoreToCrontab "# minecraft ${servername} server update at 18:00 on Sundays" - StoreToCrontab "#0 18 * * 0 cd ${serverdirectory} && ./update.sh --quiet" - updatechoice=false - fi - - # crontab automatization startup - read -p "Would you like to start your server at boot? [Y/N]: " - regex="^(Y|y|N|n)$" - while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY - done - if [[ ${REPLY} =~ ^[Yy]$ ]] - then echo "${green}automatic startup at boot...${nocolor}" - StoreToCrontab "# minecraft ${servername} server startup at boot" - StoreToCrontab "@reboot cd ${serverdirectory} && ./start.sh --quiet" - startatbootchoice=true - else echo "${yellow}no startup at boot${nocolor}" - StoreToCrontab "# minecraft ${servername} server startup at boot" - StoreToCrontab "#@reboot cd ${serverdirectory} && ./start.sh --quiet" - startatbootchoice=false - fi - - # padd crontab with two empty lines - StoreToCrontab "" - StoreToCrontab "" - - # inform user of automated crontab choices - echo "You have chosen the following configuration of your server:" - if [[ ${emailchoice} == true ]]; - then echo "crontab email output = ${blue}true${nocolor}" - else echo "crontab email output = ${red}false${nocolor}" - fi - if [[ ${backupchoice} == true ]]; - then echo "automated backups = ${blue}true${nocolor}" - else echo "automated backups = ${red}false${nocolor}" - fi - if [[ ${startstopchoice} == true ]]; - then echo "automated start and stop = ${blue}true${nocolor}" - else echo "automated start and stop = ${red}false${nocolor}" - fi - if [[ ${restartchoice} == true ]]; - then echo "automated restart = ${blue}true${nocolor}" - else echo "automated restart = ${red}false${nocolor}" - fi - if [[ ${updatechoice} == true ]]; - then echo "automated update = ${blue}true${nocolor}" - else echo "automated update = ${red}false${nocolor}" - fi - if [[ ${startatbootchoice} == true ]]; - then echo "automated start at boot = ${blue}true${nocolor}" - else echo "automated start at boot = ${red}false${nocolor}" - fi - -fi - -# check if nerdysetup is false -if [[ ${nerdysetup} == false ]]; then - - # write servername and date into crontab - date=$(date +"%Y-%m-%d %H:%M:%S") - StoreToCrontab "# Minecraft ${servername} server automatisation - executed setup.sh at ${date}" - - # crontab e-mail config - StoreToCrontab "#MAILTO=youremail@example.com" - - # define colors for tput - StoreToCrontab "TERM=xterm" - StoreToCrontab "" - - # crontab automatization backups - StoreToCrontab "# minecraft ${servername} server backup hourly at **:00" - StoreToCrontab "0 * * * * cd ${serverdirectory} && ./backup.sh --quiet" - - # crontab automated start and stop - StoreToCrontab "# minecraft ${servername} server start at 06:00" - StoreToCrontab "#0 6 * * * cd ${serverdirectory} && ./start.sh --quiet" - StoreToCrontab "# minecraft ${servername} server stop at 23:00" - StoreToCrontab "#0 23 * * * cd ${serverdirectory} && ./stop.sh --quiet" - - # crontab automatization restart - StoreToCrontab "# minecraft ${servername} server restart at 02:00 on Sundays" - StoreToCrontab "#0 12 * * 0 cd ${serverdirectory} && ./restart.sh --quiet" - - # crontab automatization updates - StoreToCrontab "# minecraft ${servername} server update at 18:00 on Sundays" - StoreToCrontab "#0 18 * * 0 cd ${serverdirectory} && ./update.sh --quiet" - - # crontab automatization startup - StoreToCrontab "# minecraft ${servername} server startup at boot" - StoreToCrontab "@reboot cd ${serverdirectory} && ./start.sh --quiet" - - # padd crontab with two empty lines - StoreToCrontab "" - StoreToCrontab "" - +if [[ ${REPLY} =~ ^[Yy]$ ]]; then + Print "ok" "accepting eula..." + echo "eula=true" >>eula.txt +else + Print "error" "declining eula..." + echo "eula=false" >>eula.txt fi -# finish messages -echo "${green}setup is complete!${nocolor}" -echo "If you would like to start your Server:" -echo "go into your ${green}${serverdirectory}${nocolor} directory and execute ${green}start.sh${nocolor}" -echo "execute like this: ${green}./start.sh${nocolor}" -echo "${cyan}God Luck and Have Fun!${nocolor} ${blue};^)${nocolor}" +# store to settings +Print "info" "storing variables in server.settings..." +StoreSettings "replaceBranch" "${branch}" +StoreSettings "replaceServerName" "${serverName}" +StoreSettings "replaceHomeDirectory" "${homeDirectory}" +StoreSettings "replaceServerDirectory" "${serverDirectory}" +StoreSettings "replaceBackupDirectory" "${backupDirectory}" +StoreSettings "replaceExecutableServerFile" "${executableServerFile}" + +# store to properties +Print "info" "storing variables in server.properties..." +StoreProperties "white-list=false" "white-list=true" +StoreProperties "enforce-whitelist=false" "enforce-whitelist=true" +StoreProperties "op-permission-level=4" "op-permission-level=3" +StoreProperties "difficulty=easy" "difficulty=normal" +StoreProperties "max-players=20" "max-players=8" +StoreProperties "view-distance=10" "view-distance=16" +StoreProperties "simulation-distance=10" "simulation-distance=8" +StoreProperties "sync-chunk-writes=true" "sync-chunk-writes=false" +StoreProperties "motd=A Minecraft Server" "motd=Hello World, I am your new Minecraft Server ;^)" + +# store to crontab +Print "info" "storing config to crontab..." +date=$(date +"%Y-%m-%d %H:%M:%S") +StoreCrontab "# minecraft ${serverName} server automatisation - executed setup.sh at $(date +"%Y-%m-%d %H:%M:%S")" +StoreCrontab "" +StoreCrontab "#MAILTO=youremail@example.com" +StoreCrontab "TERM=xterm" +StoreCrontab "" +StoreCrontab "# minecraft ${serverName} server backup hourly at **:00" +StoreCrontab "0 * * * * cd ${serverDirectory} && ./backup.sh --hourly --quiet" +StoreCrontab "# minecraft ${serverName} server backup daily at **:00" +StoreCrontab "0 0 * * * cd ${serverDirectory} && ./backup.sh --daily --quiet" +StoreCrontab "# minecraft ${serverName} server backup weekly at **:00" +StoreCrontab "0 0 * * 0 cd ${serverDirectory} && ./backup.sh --weekly --quiet" +StoreCrontab "# minecraft ${serverName} server backup monthly at **:00" +StoreCrontab "0 0 1 * * cd ${serverDirectory} && ./backup.sh --monthly --quiet" +StoreCrontab "# minecraft ${serverName} server startup at boot" +StoreCrontab "@reboot cd ${serverDirectory} && ./start.sh --quiet" +StoreCrontab "" +StoreCrontab "" + +# finish message +Print "ok" "setup is complete!" # ask user for removal of setup script -read -p "Would you like to remove the setup script? [Y/N]: " +read -p "$(date +"%H:%M:%S") prompt: would you like to remove the setup script? (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY + read -p "$(date +"%H:%M:%S") prompt: please press y or n: " REPLY done if [[ ${REPLY} =~ ^[Yy]$ ]]; then - cd ${homedirectory} + cd "${homeDirectory}" rm setup.sh - cd ${serverdirectory} + cd "${serverDirectory}" fi # ask user to start server now -read -p "Would you like to start your server now? [Y/N]: " +read -p "$(date +"%H:%M:%S") prompt: would you like to start your server now? (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY + read -p "$(date +"%H:%M:%S") prompt: please press y or n: " REPLY done if [[ ${REPLY} =~ ^[Yy]$ ]]; then - echo "${cyan}action: starting up server...${nocolor}" + Print "action" "starting up server..." ./start.sh --verbose else - echo "${green}ok: script has finished!${nocolor}" + Print "ok" "script has finished!" fi # exit with code 0 diff --git a/start.sh b/start.sh index 3c6901b..8e9246f 100644 --- a/start.sh +++ b/start.sh @@ -1,234 +1,146 @@ #!/bin/bash # minecraft server start script -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi - -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi - -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi - -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi +# read server files +source server.settings +source server.functions -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi +# parse arguments +ParseArgs "$@" +ArgHelp -# check for executable -if ! ls ${serverfile}* 1> /dev/null 2>&1; then - echo "${red}fatal: no executable found!${nocolor}" - echo "fatal: no executable found!" >> ${screenlog} - echo "$(date) fatal: no executable found!" >> fatalerror.log - exit 1 -fi +# safety checks +RootSafety +ScriptSafety -# log to debug if true -CheckDebug "executing start script" +# debug +Debug "executing $0 script" -# parsing script arguments -ParseScriptArguments "$@" +# change to server directory +ChangeServerDirectory -# padd logfile for visibility -echo "" >> ${screenlog} -echo "" >> ${screenlog} +# check for existance of executable +CheckExecutable -# write date to logfile -echo "action: ${date} executing start script" >> ${screenlog} +# look if server is running +LookForScreen -# check if server is already running -if screen -list | grep -q "\.${servername}"; then - echo "Server is already running! Type screen -r ${servername} to open the console" >> ${screenlog} - echo "${yellow}Server is already running! Type screen -r ${servername} to open the console${nocolor}" - exit 1 -fi +# check if private network is online +CheckPrivate -# check if interface is online -interfacechecks="0" -while [ ${interfacechecks} -lt 8 ]; do - if ping -c 1 ${interface} &> /dev/null - then - CheckVerbose "${green}ok: interface is online${nocolor}" - echo "ok: interface is online" >> ${screenlog} - break - else - echo "${yellow}warning: interface is offline${nocolor}" - echo "warning: interface is offline" >> ${screenlog} - fi - if [ ${interfacechecks} -eq 7 ]; then - echo "${red}fatal: interface timed out${nocolor}" - echo "fatal: interface timed out" >> ${screenlog} - fi - sleep 1s - interfacechecks=$((interfacechecks+1)) -done - -# check if dnsserver is online -networkchecks="0" -while [ ${networkchecks} -lt 8 ]; do - if ping -c 1 ${dnsserver} &> /dev/null - then - CheckVerbose "${green}ok: nameserver is online${nocolor}" - echo "ok: nameserver is online" >> ${screenlog} - break - else - echo "${yellow}warning: nameserver is offline${nocolor}" - echo "warning: nameserver is offline" >> ${screenlog} - fi - if [ ${networkchecks} -eq 7 ]; then - echo "${red}fatal: nameserver timed out${nocolor}" - echo "fatal: nameserver timed out" >> ${screenlog} - fi - sleep 1s - networkchecks=$((networkchecks+1)) -done +# check if public network is online +CheckPublic # user information -CheckQuiet "Starting Minecraft server. To view window type screen -r ${servername}." -CheckQuiet "To minimise the window and let the server run in the background, press Ctrl+A then Ctrl+D" -echo "action: starting ${servername} server..." >> ${screenlog} -CheckVerbose "${cyan}action: starting ${servername} server...${nocolor}" +Print "info" "starting minecraft server. to view window type screen -r ${serverName}." +Print "info" "to minimise the window and let the server run in the background, press ctrl+a then ctrl+d" # main start commmand -${screen} -dmSL ${servername} -Logfile ${screenlog} ${java} -server ${mems} ${memx} ${threadcount} -jar ${serverfile} -nogui -${screen} -r ${servername} -X colon "logfile flush 1^M" +Start # check if screen is avaible -counter="0" -startchecks="0" -while [ ${startchecks} -lt 10 ]; do - if screen -list | grep -q "\.${servername}"; then - counter=$((counter+1)) - fi - if [ ${counter} -eq 2 ]; then - break - fi - startchecks=$((startchecks+1)) - sleep 1s -done +AwaitStart # if no screen output error -if ! screen -list | grep -q "${servername}"; then - echo "fatal: something went wrong - server failed to start!" >> ${screenlog} - echo "${red}fatal: something went wrong - server failed to start!${nocolor}" +if ! screen -list | grep -q "${serverName}"; then + Log "fatal" "something went wrong - server failed to start!" "${screenLog}" + Print "fatal" "something went wrong - server failed to start!" + Print "info" "crash dump - last 10 lines of ${screenLog}" + tail -10 "${screenLog}" exit 1 fi # succesful start sequence -echo "ok: server is on startup..." >> ${screenlog} -CheckQuiet "${green}ok: server is on startup...${nocolor}" +Log "ok" "server is on startup..." "${screenLog}" +Print "ok" "server is on startup..." # check if screenlog contains start comfirmation count="0" counter="0" -startupchecks="0" -while [ ${startupchecks} -lt 120 ]; do - if tail ${screenlog} | grep -q "Query running on"; then - echo "ok: server startup successful - query up and running" >> ${screenlog} - CheckQuiet "${green}ok: server startup successful - query up and running${nocolor}" +startupChecks="0" +while [ ${startupChecks} -lt 120 ]; do + if tail "${screenLog}" | grep -q "Time elapsed:"; then + Log "ok" "server startup successful - up and running" "${screenLog}" + Print "ok" "server startup successful - up and running" break fi - if tail -20 ${screenlog} | grep -q "FAILED TO BIND TO PORT"; then - echo "fatal: server port is already in use - please change to another port" >> ${screenlog} - echo "${red}fatal: server port is already in use - please change to another port${nocolor}" + if tail -20 "${screenLog}" | grep -q "FAILED TO BIND TO PORT"; then + Log "error" "server port is already in use - please change to another port" "${screenLog}" + Print "error" "server port is already in use - please change to another port" + exit 1 + fi + if tail -20 "${screenLog}" | grep -q "Address already in use"; then + Log "error" "server address is already in use - please change to another port" "${screenLog}" + Print "error" "server address is already in use - please change to another port" + exit 1 + fi + if tail -20 "${screenLog}" | grep -q "session.lock: already locked"; then + Log "error" "session is locked - is the world in use by another instance?" "${screenLog}" + Print "error" "session is locked - is the world in use by another instance?" exit 1 fi - if ! screen -list | grep -q "${servername}"; then - echo "fatal: something went wrong - server appears to have crashed!" >> ${screenlog} - echo "${red}fatal: something went wrong - server appears to have crashed!${nocolor}" - echo "info: crash dump - last 10 lines of ${screenlog}" - tail -10 ${screenlog} + if ! screen -list | grep -q "${serverName}"; then + Log "fatal" "something went wrong - server appears to have crashed!" "${screenLog}" + Print "fatal" "something went wrong - server appears to have crashed!" + Print "info" "crash dump - last 10 lines of ${screenLog}" + tail -10 "${screenLog}" exit 1 fi - if tail ${screenlog} | grep -q "Preparing spawn area"; then - counter=$((counter+1)) + if tail "${screenLog}" | grep -q "Preparing spawn area"; then + counter=$((counter + 1)) fi - if tail ${screenlog} | grep -q "Environment"; then + if tail "${screenLog}" | grep -q "Environment"; then if [ ${count} -eq 0 ]; then - CheckVerbose "info: server is loading the environment..." + Print "info" "server is loading the environment..." fi - count=$((count+1)) + count=$((count + 1)) fi - if tail ${screenlog} | grep -q "Reloading ResourceManager"; then - count=$((count+1)) + if tail "${screenLog}" | grep -q "Reloading ResourceManager"; then + count=$((count + 1)) fi - if tail ${screenlog} | grep -q "Starting minecraft server"; then - count=$((count+1)) + if tail "${screenLog}" | grep -q "Starting minecraft server"; then + count=$((count + 1)) fi if [ ${counter} -ge 10 ]; then - CheckVerbose "info: server is preparing spawn area..." + Print "info" "server is preparing spawn area..." counter="0" fi - if [ ${count} -eq 0 ] && [ ${startupchecks} -eq 20 ]; then - echo "warning: the server could be crashed" >> ${screenlog} - echo "${yellow}warning: the server could be crashed${nocolor}" + if [ ${count} -eq 0 ] && [ ${startupChecks} -eq 20 ]; then + Log "warn" "the server could be crashed" "${screenLog}" + Print "warn" "the server could be crashed" exit 1 fi - startupchecks=$((startupchecks+1)) + startupChecks=$((startupChecks + 1)) sleep 1s done # check if screenlog does not contain startup confirmation -if ! tail ${screenlog} | grep -q "Query running on"; then - echo "warning: server startup unsuccessful - perhaps query is disabled" >> ${screenlog} - echo "${yellow}warning: server startup unsuccessful - perhaps query is disabled${nocolor}" +if ! tail "${screenLog}" | grep -q "Time elapsed:"; then + Log "warn" "server startup unsuccessful" "${screenLog}" + Print "warn" "server startup unsuccessful" + Print "info" "crash dump - last 10 lines of ${screenLog}" + tail -10 "${screenLog}" fi -# enables the watchdog script for backup integrity -if [[ ${enablewatchdog} == true ]]; then - CheckVerbose "info: activating watchdog..." - ./watchdog.sh & -fi +# enable worker script +nice -n 19 ./worker.sh & -# check if user wants to send welcome messages -if [[ ${welcomemessage} == true ]]; then - CheckVerbose "info: activating welcome messages..." - ./welcome.sh & +if [[ "${enableBackupsWatchdog}" == true ]]; then + Print "info" "activating backups watchdog..." fi - -# check if user wants to enable task execution -if [[ ${enabletasks} == true ]]; then - CheckVerbose "info: activating task execution..." - ./worker.sh & +if [[ "${enableWelcomeMessage}" == true ]]; then + Print "info" "activating welcome messages..." fi - -# if set to true change automatically to server console -if [[ ${changetoconsole} == true ]]; then - CheckVerbose "info: changing to server console..." - screen -r ${servername} +if [[ "${enableAutoStartOnCrash}" == true ]]; then + Print "info" "activating auto start on crash..." +fi +if [[ "${changeToConsole}" == true ]]; then + Print "info" "changing to server console..." + screen -r "${serverName}" fi -# user information -CheckQuiet "If you would like to change to server console - type ${green}screen -r ${servername}${nocolor}" +Print "info" "if you would like to change to server console - type screen -r ${serverName}" -# log to debug if true -CheckDebug "executed start script" +Debug "executed $0 script" -# exit with code 0 exit 0 diff --git a/stop.sh b/stop.sh index e9f89ae..bda3f9b 100644 --- a/stop.sh +++ b/stop.sh @@ -1,103 +1,48 @@ #!/bin/bash # minecraft server stop script -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi +# read server files +source server.settings +source server.functions -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi +# parse arguments +ParseArgs "$@" +ArgHelp -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi +# safety checks +RootSafety +ScriptSafety -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi +# debug +Debug "executing $0 script" -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi +# change to server directory +ChangeServerDirectory -# log to debug if true -CheckDebug "executing stop script" - -# parsing script arguments -ParseScriptArguments "$@" - -# write date to logfile -echo "action: ${date} executing stop script" >> ${screenlog} +# check for existance of executable +CheckExecutable -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - echo "server is not currently running!" >> ${screenlog} - echo "${yellow}server is not currently running!${nocolor}" - exit 1 -fi +# look if server is running +CheckScreen -# check if immediately is specified -if ! [[ ${immediately} == true ]]; then - # countdown - counter="60" - while [ ${counter} -gt 0 ]; do - if [[ "${counter}" =~ ^(60|40|20|10|5|4|3|2|1)$ ]];then - CheckQuiet "${blue}[Script]${nocolor} server is stopping in ${counter} seconds" - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"server is stopping in ${counter} seconds\"}]$(printf '\r')" - fi - counter=$((counter-1)) - sleep 1s - done -fi +# prints countdown to screen +Countdown "stopping" # server stop -CheckQuiet "stopping server..." -PrintToScreen "say stopping server..." -PrintToScreen "stop" +Stop -# check if server stopped -stopchecks="0" -while [ $stopchecks -lt 30 ]; do - if ! screen -list | grep -q "\.${servername}"; then - break - fi - stopchecks=$((stopchecks+1)) - sleep 1; -done +# awaits server stop +AwaitStop # force quit server if not stopped -if screen -list | grep -q "${servername}"; then - echo "${yellow}minecraft server still hasn't closed after 30 seconds, closing screen manually${nocolor}" - screen -S ${servername} -X quit -fi +ForceQuit # output confirmed stop -echo "server successfully stopped!" >> ${screenlog} -CheckQuiet "${green}server successfully stopped!${nocolor}" +Log "ok" "server successfully stopped" "${screenLog}" +Print "ok" "server successfully stopped" # log to debug if true -CheckDebug "executed stop script" +Debug "executed $0 script" # exit with code 0 exit 0 diff --git a/update.sh b/update.sh index 781b49b..cb65446 100644 --- a/update.sh +++ b/update.sh @@ -1,221 +1,102 @@ #!/bin/bash # minecraft server update script -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi - -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi - -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi - -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi - -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi - -# log to debug if true -CheckDebug "executing update script" - -# parsing script arguments -ParseScriptArguments "$@" - -# write date to logfile -echo "action: ${date} executing update script" >> ${screenlog} - -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - - # remove all older safety backups - if [[ -s "${backupdirectory}/cached/update-"* ]]; then - rm ${backupdirectory}/cached/update-* - fi +# read server files +source server.settings +source server.functions - # create backup - CheckVerbose "${blue}backing up...${nocolor}" - tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/cached/update-${newdaily}.tar.gz +# parse arguments +ParseArgs "$@" +ArgHelp - # check if safety backup exists - if ! [[ -s "${backupdirectory}/cached/update-${newdaily}.tar.gz" ]]; then - echo "${yellow}warning: safety backup failed - proceeding to server update${nocolor}" - echo "warning: safety backup failed - proceeding to server update" >> ${screenlog} - else - echo "ok: created ${backupdirectory}/cached/update-${newdaily}.tar.gz as a safety backup" >> ${backuplog} - echo "" >> ${backuplog} - fi - - # Test internet connectivity and update on success - wget --spider --quiet https://launcher.mojang.com/v1/objects/a16d67e5807f57fc4e550299cf20226194497dc2/server.jar - if [ "$?" != 0 ]; then - echo "${yellow}warning: Unable to connect to Mojang API. Skipping update...${nocolor}" - echo "warning: Unable to connect to Mojang API. Skipping update..." >> ${screenlog} - else - CheckQuiet "${green}downloading newest server version...${nocolor}" - echo "downloading newest server version..." >> ${screenlog} - # check if already on newest version - if [[ "${serverfile}" = *"minecraft-server.1.17.1.jar" ]]; then - CheckVerbose "You are running the newest server version - skipping update" - echo "You are running the newest server version - skipping update" >> ${screenlog} - else - wget -q -O minecraft-server.1.17.1.jar https://launcher.mojang.com/v1/objects/a16d67e5807f57fc4e550299cf20226194497dc2/server.jar - # update serverfile variable in server.settings - newserverfile="${serverdirectory}/minecraft-server.1.17.1.jar" - # if new serverfile exists remove oldserverfile - if [ -f "${newserverfile}" ]; then - CheckVerbose "${green}ok: updating server.settings for startup with new server version 1.17.1${nocolor}" - sed -i "s|${serverfile}|${newserverfile}|g" server.settings - # remove old serverfile if it exists - if [ -f "${serverfile}" ]; then - rm ${serverfile} - fi - else - echo "${yellow}warning: could not remove old serverfile ${serverfile} because new serverfile ${newserverfile} is missing${nocolor}" - echo "Server will startup with old serverfile ${serverfile}" - fi - fi - fi +# safety checks +RootSafety +ScriptSafety - # remove scripts from serverdirectory - RemoveScriptsFromServerDirectory +# debug +Debug "executing $0 script" - # downloading scripts from github - DownloadScriptsFromGitHub +# change to server directory +ChangeServerDirectory - # make selected scripts executable - MakeScriptsExecutable +# check for existance of executable +CheckExecutable - # restart the server - CheckQuiet "${cyan}action: restarting server...${nocolor}" - ./start.sh "$@" - exit 0 -fi +# look if server is running +CheckScreen -# check if immediately is specified -if ! [[ ${immediately} == true ]]; then - # countdown - counter="60" - while [ ${counter} -gt 0 ]; do - if [[ "${counter}" =~ ^(60|40|20|10|5|4|3|2|1)$ ]];then - CheckQuiet "${blue}[Script]${nocolor} server is updating in ${counter} seconds" - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"server is updating in ${counter} seconds\"}]$(printf '\r')" - fi - counter=$((counter-1)) - sleep 1s - done -fi +# prints countdown to screen +Countdown "updating" # server stop -CheckQuiet "${cyan}action: stopping server...${nocolor}" -PrintToScreen "say stopping server..." -PrintToScreen "stop" - -# check if server stopped -stopchecks="0" -while [ $stopchecks -lt 30 ]; do - if ! screen -list | grep -q "\.${servername}"; then - break - fi - stopchecks=$((stopchecks+1)) - sleep 1; -done +Stop + +# awaits server stop +AwaitStop # force quit server if not stopped -if screen -list | grep -q "${servername}"; then - echo "${yellow}minecraft server still hasn't closed after 30 seconds, closing screen manually${nocolor}" - screen -S ${servername} -X quit -fi +ForceQuit -# remove all older safety backups -if [[ -s "${backupdirectory}/cached/update-"* ]]; then - rm ${backupdirectory}/cached/update-* -fi +# output confirmed stop +Log "ok" "server successfully stopped" "${screenLog}" +Print "ok" "server successfully stopped" # create backup -CheckVerbose "${blue}backing up...${nocolor}" -tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/cached/update-${newdaily}.tar.gz +CachedBackup "update" -# check if safety backup exists -if ! [[ -s "${backupdirectory}/cached/update-${newdaily}.tar.gz" ]]; then - echo "${yellow}warning: safety backup failed - proceeding to server update${nocolor}" - echo "warning: safety backup failed - proceeding to server update" >> ${screenlog} -else - echo "created ${backupdirectory}/cached/update-${newdaily}.tar.gz as a safety backup" >> ${backuplog} - echo "" >> ${backuplog} -fi +# update from url +url="https://launcher.mojang.com/v1/objects/125e5adf40c659fd3bce3e66e67a16bb49ecc1b9/server.jar" +version="1.18.1" # Test internet connectivity and update on success -wget --spider --quiet https://launcher.mojang.com/v1/objects/a16d67e5807f57fc4e550299cf20226194497dc2/server.jar +wget --spider --quiet "${url}" if [ "$?" != 0 ]; then - echo "${yellow}warning: Unable to connect to Mojang API. Skipping update...${nocolor}" - echo "warning: Unable to connect to Mojang API. Skipping update..." >> ${screenlog} + Log "warn" "unable to connect to mojang api skipping update..." "${screenLog}" + Print "warn" "unable to connect to mojang api skipping update..." else - CheckQuiet "${green}downloading newest server version...${nocolor}" - echo "downloading newest server version..." >> ${screenlog} + Log "action" "downloading newest server version..." "${screenLog}" + Print "action" "downloading newest server version..." # check if already on newest version - if [[ "${serverfile}" = *"minecraft-server.1.17.1.jar" ]]; then - CheckVerbose "You are running the newest server version - skipping update" - echo "You are running the newest server version - skipping update" >> ${screenlog} + if [[ "${executableServerFile}" = *"minecraft-server.${version}.jar" ]]; then + Log "info" "you are running the newest server version - skipping update" "${screenLog}" + Print "info" "you are running the newest server version - skipping update" else - wget -q -O minecraft-server.1.17.1.jar https://launcher.mojang.com/v1/objects/a16d67e5807f57fc4e550299cf20226194497dc2/server.jar + wget -q -O "minecraft-server.${version}.jar" "${url}" # update serverfile variable in server.settings - newserverfile="${serverdirectory}/minecraft-server.1.17.1.jar" + newExecutableServerFile="${serverDirectory}/minecraft-server.${version}.jar" # if new serverfile exists remove oldserverfile - if [ -f "${newserverfile}" ]; then - CheckVerbose "${green}ok: updating server.settings for startup with new server version 1.17.1${nocolor}" - sed -i "s|${serverfile}|${newserverfile}|g" server.settings + if [ -s "${newExecutableServerFile}" ]; then + Log "ok" "download sucessfull" + Print "ok" "download sucessfull" + Log "info" "updating server.settings for startup with new server version ${version}" "${screenLog}" + Print "info" "updating server.settings for startup with new server version ${version}" + sed -i "s|${executableServerFile}|${newExecutableServerFile}|g" "server.settings" # remove old serverfile if it exists - if [ -f "${serverfile}" ]; then - rm ${serverfile} + if [ -s "${executableServerFile}" ]; then + rm "${executableServerFile}" fi else - echo "${yellow}warning: could not remove old serverfile ${serverfile} because new serverfile ${newserverfile} is missing${nocolor}" - echo "Server will startup with old serverfile ${serverfile}" + Print "warn" "could not remove old server-file ${executableServerFile} because new server-file ${newExecutableServerFile} is missing" + Print "info" "server will startup with old server-file ${executableServerFile}" fi fi fi # remove scripts from serverdirectory -RemoveScriptsFromServerDirectory +RemoveScripts # downloading scripts from github -DownloadScriptsFromGitHub +DownloadScripts # make selected scripts executable -MakeScriptsExecutable +ExecutableScripts # restart the server -CheckQuiet "${cyan}restarting server...${nocolor}" -./start.sh "$@" +Print "action" "restarting server..." +./start.sh --force "$@" # log to debug if true -CheckDebug "executed update script" +Debug "executed $0 script" # exit with code 0 exit 0 diff --git a/vent.sh b/vent.sh index 38e2356..b9a78f9 100644 --- a/vent.sh +++ b/vent.sh @@ -3,166 +3,73 @@ # WARNING do not execute unless you want to delete your server -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi +# read server files +source server.settings +source server.functions -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi +# parse arguments +ParseArgs "$@" +ArgHelp -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi +# safety checks +RootSafety +ScriptSafety -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi +# debug +Debug "executing $0 script" -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi +# change to server directory +ChangeServerDirectory -# log to debug if true -CheckDebug "executing vent script" +# check for existance of executable +CheckExecutable -# parsing script arguments -ParseScriptArguments "$@" +# look if server is running +CheckScreen # user safety function for confirmation -echo "${yellow}Are you sure you want to vent your server?${nocolor}" -read -p "If so, please type ${red}CONFIRM VENTING${nocolor} " -if [[ ${REPLY} == "CONFIRM VENTING" ]]; then - echo "User confirmed venting - I will self-destruct now" +Print "warn" "are you sure you want to vent your server?" +read -p "$(date +"%H:%M:%S") prompt: if so, please type confirm venting " +if [[ ${REPLY} == "confirm venting" ]]; then + Print "info" "you confirmed venting - server will self-destruct now" else - echo "wrong token - please try again" + Print "error" "wrong venting token - you may try again" exit 1 fi -# write date to logfile -echo "action: ${date} executing self-destruct script" >> ${screenlog} - -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - echo "server is not currently running!" >> ${screenlog} - echo "${yellow}server is not currently running!${nocolor}" - counter="10" - # check if immediately is specified - if ! [[ ${immediately} == true ]]; then - while [ ${counter} -gt 0 ]; do - if [[ "${counter}" =~ ^(10|9|8|7|6|5|4|3|2|1)$ ]]; then - CheckQuiet "${blue}[Script]${nocolor} ${red}server is self-destructing in ${counter} seconds${nocolor}" - fi - counter=$((counter-1)) - sleep 1s - done - fi - cd ${homedirectory} - # remove crontab - crontab -r - # remove serverdirectory - echo "deleting server..." - rm -r ${servername} - # check if vent was successful - if ! [ -d "${serverdirectory}" ]; then - # game over terminal screen - PrintGameOver - exit 0 - else - # error if serverdirectory still exists - echo "${red}venting failed!${nocolor}" - exit 1 - fi -fi - -# warning -echo "${blue}[Script]${nocolor} ${red}WARNING: venting startet!${nocolor}" -screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"WARNING: venting startet!\",\"color\":\"red\"}]$(printf '\r')" - -# sleep for 2 seconds -sleep 2s - -# check if immediately is specified -if ! [[ ${immediately} == true ]]; then - # countdown - counter="120" - while [ ${counter} -gt 0 ]; do - if [[ "${counter}" =~ ^(120|60|40|20|10|9|8|7|6|5|4|3|2|1)$ ]]; then - CheckQuiet "${blue}[Script]${nocolor} ${red}server is self-destructing in ${counter} seconds${nocolor}" - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"server is self-destructing in ${counter} seconds\",\"color\":\"red\"}]$(printf '\r')" - fi - counter=$((counter-1)) - sleep 1s - done -fi +# prints countdown to screen +Countdown "self-destructing" # game over -echo "${blue}[Script]${nocolor} ${red}GAME OVER${nocolor}" -screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"GAME OVER\",\"color\":\"red\"}]$(printf '\r')" - -# sleep 2 seconds -sleep 2s - -# stop command -echo "stopping server..." -screen -Rd ${servername} -X stuff "say deleting server...$(printf '\r')" -screen -Rd ${servername} -X stuff "stop$(printf '\r')" - -# check if server stopped -stopchecks="0" -while [ $stopchecks -lt 30 ]; do - if ! screen -list | grep -q "\.${servername}"; then - break - fi - stopchecks=$((stopchecks+1)) - sleep 1; -done +Screen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"GAME OVER\",\"color\":\"red\"}]" -# force quit server if not stopped -if screen -list | grep -q "${servername}"; then - echo "${yellow}minecraft server still hasn't closed after 30 seconds, closing screen manually${nocolor}" - screen -S ${servername} -X quit -fi +# server stop +Stop -# sleep 2 seconds -sleep 2s +# awaits server stop +AwaitStop -cd ${homedirectory} +# force quit server if not stopped +ForceQuit + +cd "${homeDirectory}" # remove crontab crontab -r # remove serverdirectory -echo "deleting server..." -rm -r ${servername} +Print "action" "deleting server..." +rm -r "${serverName}" # check if vent was successful -if ! [ -d "${serverdirectory}" ]; then +if ! [ -d "${serverDirectory}" ]; then # game over terminal screen - PrintGameOver - exit 0 + GameOver else # error if serverdirectory still exists - echo "${red}venting failed!${nocolor}" + Print "error" "venting failed!" exit 1 fi +# debug +Debug "executed $0 script" + # exit with code 0 exit 0 diff --git a/watchdog.sh b/watchdog.sh deleted file mode 100644 index 8d8fc2f..0000000 --- a/watchdog.sh +++ /dev/null @@ -1,87 +0,0 @@ -#!/bin/bash - -# minecraft server watchdog script -# can be executed detached with ./watchdog.sh & - -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi - -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi - -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi - -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi - -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi - -# write date to logfile -echo "${date} executing watchdog script" >> ${screenlog} - -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - echo "server is not currently running!" >> ${screenlog} - echo "${yellow}server is not currently running!${nocolor}" - exit 1 -fi - -# write a function that checks if backups are done regularly -# if any irregularities are detected notify via ingame or logfiles -lastabsoluteworldsize="65536" -lastabsolutebackupsize="65536" -counter="0" -while true; do - if [[ ${counter} -eq 120 ]]; then - . ./server.settings - timestamp=$(date +"%H:%M:%S") - lasttimestamp=$(date -d -"2 minute" +"%H:%M:%S") - if [[ ${absoluteworldsize} < $((${lastabsoluteworldsize} - 65536)) ]]; then - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"info: your world-size is getting smaller - this may result in a corrupted world\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"world-size at ${lasttimestamp} was ${lastabsoluteworldsize} bytes, world-size at ${timestamp} is ${absoluteworldsize} bytes\"}]}}}]$(printf '\r')" - echo "info: your world-size is getting smaller - this may result in a corrupted world" >> ${backuplog} - echo "info: world-size at ${timestamp} was ${lastabsoluteworldsize} bytes, world-size at ${lasttimestamp} is ${absoluteworldsize} bytes" >> ${backuplog} - echo "" >> ${backuplog} - fi - if [[ ${absolutebackupsize} < $((${lastabsolutebackupsize} - 65536)) ]]; then - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"info: your backup-size is getting smaller - this may result in corrupted backups\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"backup-size at ${lasttimestamp} was ${lastabsolutebackupsize} bytes, backup-size at ${timestamp} is ${absolutebackupsize} bytes\"}]}}}]$(printf '\r')" - echo "info: your backup-size is getting smaller - this may result in corrupted backups" >> ${backuplog} - echo "info: backup-size at ${timestamp} was ${lastabsolutebackupsize} bytes, backup-size at ${lasttimestamp} is ${absolutebackupsize} bytes" >> ${backuplog} - echo "" >> ${backuplog} - fi - lastabsoluteworldsize="${absoluteworldsize}" - lastabsolutebackupsize="${absolutebackupsize}" - counter="0" - fi - if ! screen -list | grep -q "\.${servername}"; then - exit 0 - fi - counter=$((counter+1)) - sleep 1s -done diff --git a/welcome.sh b/welcome.sh deleted file mode 100644 index 95f1630..0000000 --- a/welcome.sh +++ /dev/null @@ -1,73 +0,0 @@ -#!/bin/bash - -# minecraft server welcome script -# can be executed detached with ./welcome.sh & - -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi - -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi - -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi - -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi - -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi - -# write date to logfile -echo "${date} executing welcome script" >> ${screenlog} - -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - echo "server is not currently running!" >> ${screenlog} - echo "${yellow}server is not currently running!${nocolor}" - exit 1 -fi - -# array with different welcome messages -welcome=( "Welcome on my server" "A warm welcome to" "Greetings" "Hello to" "Welcome aboard" "Make yourself at home" "Have a nice time" ) - -# check every second if a player joins and welcome them by name with a random welcome message -while true; do - size=${#welcome[@]} - index=$(($RANDOM % $size)) - timestamp=$(date +"%H:%M:%S") - if tail -1 screen.log | grep -q "joined the game"; then - welcomemsg=${welcome[$index]} - player=$(tail -1 screen.log | grep -oP '.*?(?=joined the game)' | cut -d ' ' -f 4- | sed 's/.$//') - screen -Rd ${servername} -X stuff "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"${welcomemsg} ${player}\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"player ${player} joined at ${timestamp}\"}]}}}]$(printf '\r')" - fi - if ! screen -list | grep -q "\.${servername}"; then - exit 0 - fi - sleep 1s -done diff --git a/worker.sh b/worker.sh index c176fae..1bb3069 100644 --- a/worker.sh +++ b/worker.sh @@ -1,87 +1,91 @@ #!/bin/bash - # minecraft server worker script -# can be executed detached with ./worker.sh & - -# root safety check -if [ $(id -u) = 0 ]; then - echo "$(tput bold)$(tput setaf 1)please do not run me as root :( - this is dangerous!$(tput sgr0)" - exit 1 -fi -# read server.functions file with error checking -if [[ -s "server.functions" ]]; then - . ./server.functions -else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.functions is missing$(tput sgr0)" - exit 1 -fi +# read server files +source server.settings +source server.functions -# read server.properties file with error checking -if ! [[ -s "server.properties" ]]; then - echo "$(date) fatal: server.properties is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" - exit 1 -fi +# parse arguments +ParseArgs "$@" +ArgHelp -# read server.settings file with error checking -if [[ -s "server.settings" ]]; then - . ./server.settings -else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log - echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" - exit 1 -fi +# safety checks +RootSafety +ScriptSafety -# change to server directory with error checking -if [ -d "${serverdirectory}" ]; then - cd ${serverdirectory} -else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log - echo "${red}fatal: serverdirectory is missing${nocolor}" - exit 1 -fi +# debug +Debug "executing $0" -# write date to logfile -echo "${date} executing worker script" >> ${screenlog} +# change to server directory +ChangeServerDirectory # check if server is running -if ! screen -list | grep -q "\.${servername}"; then - echo "server is not currently running!" >> ${screenlog} - echo "${yellow}server is not currently running!${nocolor}" - exit 1 -fi +CheckScreen -# check every second if a player with permission request a task -linebuffer=$(tail -1 "${screenlog}") -lastlinebuffer=${linebuffer} +# run various functions every second until server exits +counter=0 while true; do - linebuffer=$(tail -1 "${screenlog}") - if [[ ! ${linebuffer} == ${lastlinebuffer} ]]; then - # check if safety backup is enabled - if [[ ${enablesafetybackupstring} == true ]]; then - CheckSafetyBackupString + if ! [[ -d ${serverDirectory} ]]; then + exit 0 + fi + + if ! screen -list | grep -q "\.${serverName}"; then + Debug "executed $0 script" + exit 0 + fi + + lineBuffer=$(tail -1 "${screenLog}") + if [[ ! ${lineBuffer} == ${lastLineBuffer} ]]; then + if [[ ${enableWelcomeMessage} == true ]]; then + size=${#welcome[@]} + index=$((${RANDOM} % ${size})) + timeStamp=$(date +"%H:%M:%S") + if tail -1 screen.log | grep -q "joined the game"; then + welcomeMessage=${welcome[$index]} + player=$(tail -1 screen.log | grep -oP '.*?(?=joined the game)' | cut -d ' ' -f 4- | sed 's/.$//') + TellrawScript "${welcomeMessage} ${player}" "player ${player} joined at ${timeStamp}" + fi + fi + + Help + ListTasks + ListBackups + if [[ ${enablePerformBackup} == true ]]; then + PerformBackup fi - # check if safety backup is enabled - if [[ ${enableconfirmrestartstring} == true ]]; then - CheckConfirmRestartString + if [[ ${enablePerformRestart} == true ]]; then + PerformRestart fi - # check if safety backup is enabled - if [[ ${enableconfirmupdatestring} == true ]]; then - CheckConfirmUpdateString + if [[ ${enablePerformUpdate} == true ]]; then + PerformUpdate fi - # check if safety backup is enabled - if [[ ${enableconfirmresetstring} == true ]]; then - CheckConfirmResetString + if [[ ${enablePerformReset} == true ]]; then + PerformReset fi fi - # store last line of screen log into buffer - linebuffer=$(tail -1 "${screenlog}") - # exit check if server is shut down - if ! screen -list | grep -q "\.${servername}"; then - exit 0 + + if [[ ${enableBackupsWatchdog} == true ]]; then + if [[ ${counter} -eq 120 ]]; then + source server.settings + timeStamp=$(date +"%H:%M:%S") + lastTimeStamp=$(date -d -"2 minute" +"%H:%M:%S") + if [[ ${worldSizeBytes} -lt $((${lastWorldSizeBytes} - 65536)) ]]; then + Log "warn" "your world-size is getting smaller - this may result in a corrupted world" "${backupLog}" + Log "info" "world-size at ${lastTimeStamp} was ${lastWorldSizeBytes} bytes, world-size at ${timeStamp} is ${worldSizeBytes} bytes" "${backupLog}" + TellrawScript "warn: your world-size is getting smaller - this may result in a corrupted world" "world-size at ${lastTimeStamp} was ${lastWorldSizeBytes} bytes, world-size at ${timeStamp} is ${worldSizeBytes} bytes" + fi + if [[ ${backupSizeBytes} -lt $((${lastBackupSizeBytes} - 65536)) ]]; then + Log "warn" "your backup-size is getting smaller - this may result in corrupted backups" "${backupLog}" + Log "info" "backup-size at ${lastTimeStamp} was ${lastBackupSizeBytes} bytes, backup-size at ${timeStamp} is ${backupSizeBytes} bytes" "${backupLog}" + TellrawScript "warn: your backup-size is getting smaller - this may result in corrupted backups" "backup-size at ${lastTimeStamp} was ${lastBackupSizeBytes} bytes, backup-size at ${timeStamp} is ${backupSizeBytes} bytes" + fi + lastWorldSizeBytes=${worldSizeBytes} + lastBackupSizeBytes=${backupSizeBytes} + counter=0 + fi fi - lastlinebuffer=${linebuffer} + + lastLineBuffer="${lineBuffer}" + counter=$((counter + 1)) sleep 1s done