From f4a9683bac6d20bf623e3f3179ad48d4b49b892d Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Wed, 6 Oct 2021 16:28:57 +0200 Subject: [PATCH 001/115] more functions --- server.functions | 318 ++++++++++++++++++++++++++--------------------- 1 file changed, 177 insertions(+), 141 deletions(-) diff --git a/server.functions b/server.functions index cff8120..62b396c 100644 --- a/server.functions +++ b/server.functions @@ -1,20 +1,21 @@ #!/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 -# if you know what you are doing, feel free to tinker with them ;^) +# 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 ;^) # function for parsing arguments for a script function ParseScriptArguments { - immediately=false + now=false quiet=false verbose=false while [[ $# -gt 0 ]]; do case "$1" in - -i) - immediately=true + -n) + now=true ;; -q) quiet=true @@ -22,8 +23,8 @@ function ParseScriptArguments { -v) verbose=true ;; - --immediately) - immediately=true + --now) + now=true ;; --quiet) quiet=true @@ -39,130 +40,158 @@ function ParseScriptArguments { 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} - fi -} + + # check if verbose mode is on function CheckVerbose { if [[ ${verbose} == true ]]; then - echo "${1}" + return true + fi +} +# checks if debug mode is on +function CheckDebug { + if [[ ${enabledebug} == true ]]; then + return true fi } # check if quiet mode is on function CheckQuiet { - if ! [[ ${quiet} == true ]]; then - echo "${1}" + if [[ ${quiet} == true ]]; then + return true fi } -# prints all input to screen terminal +# prints all unpit to terminal +function PrintToTerminal { + if [[ $1 == "ok" ]]; then + echo "${green}ok: ${2}${nocolor}" + fi + if [[ $1 == "info" ]]; then + echo "${nocolor}info: ${2}${nocolor}" + fi + if [[ $1 == "warn" ]]; then + echo "${yellow}warn: ${2}${nocolor}" + fi + if [[ $1 == "error" ]]; then + echo "${red}error: ${2}${nocolor}" + fi + if [[ $1 == "fatal" ]]; then + echo "${red}fatal: ${2}${nocolor}" + fi + if [[ $1 == "action" ]]; then + echo "${cyan}action: ${2}${nocolor}" + fi +} +# prints all input to screen function PrintToScreen { screen -Rd ${servername} -X stuff "${1}$(printf '\r')" } +# prints all input to log +function PrintToLog { + if [[ $1 == "ok" ]]; then + echo "ok: ${2}" >> "${3}" + fi + if [[ $1 == "info" ]]; then + echo "info: ${2}" >> "${3}" + fi + if [[ $1 == "warn" ]]; then + echo "warn: ${2}" >> "${3}" + fi + if [[ $1 == "error" ]]; then + echo "error: ${2}" >> "${3}" + fi + if [[ $1 == "fatal" ]]; then + echo "fatal: ${2}" >> "${3}" + fi + if [[ $1 == "action" ]]; then + echo "action: ${2}" >> "${3}" + fi +} -# prints colourful success messages into screen +# prints success messages to terminal +function PrintToTerminalBackupSuccess { + PrintToTerminal "ok" "added ${backupdirectory}/hourly/${servername}-${1}.tar.gz" + PrintToTerminal "ok" "removed ${backupdirectory}/hourly/${servername}-${2}.tar.gz" + PrintToTerminal "ok" "current world size: ${worldsize}, current backup size: ${backupsize}, current disk space: ${diskspace}" + PrintToTerminal "ok" "time spent on backup process: ${timespent} milliseconds, compression ratio: ${compressedbackup}/${worldsize}" +} +# prints success messages to 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')" + PrintToScreen "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}\"}]}}}]" } # 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} -} -# 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}" + PrintToLog "ok" "added ${backupdirectory}/hourly/${servername}-${1}.tar.gz" "${backuplog}" + PrintToLog "ok" "removed ${backupdirectory}/hourly/${servername}-${2}.tar.gz" "${backuplog}" + PrintToLog "ok" "current world size: ${worldsize}, current backup size: ${backupsize}, current disk space: ${diskspace}" "${backuplog}" + PrintToLog "ok" "time spent on backup process: ${timespent} milliseconds, compression ratio: ${compressedbackup}/${worldsize}" "${backuplog}" + echo "" >> "${backuplog}" } -# prints colourful backup already exists message into screen +# prints backup already exists to terminal +function PrintToTerminalBackupAlreadyExists { + PrintToTerminal "error" "could not create new ${1}-backup - backup already exists" +} +# prints backup already exists to 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')" + PrintToScreen "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\"}]}}}]" } -# prints backup already exists to backup log +# prints backup already exists to log function PrintToLogBackupAlreadyExists { - echo "warning: could not create new ${1}-backup" >> ${backuplog} - echo "warning: backup already exists" >> ${backuplog} - echo "" >> ${backuplog} -} -# prints backup already exists to terminal -function PrintToTerminalBackupAlreadyExists { - echo "${yellow}warning: could not create new ${1}-backup - backup already exists${nocolor}" + PrintToLog "error" "could not create new ${1}-backup - backup already exists" "${backuplog}" + echo "" >> "${backuplog}" } -# prints colorful disk space warning message into screen +# prints disk space warnig to terminal +function PrintToTerminalDiskSpaceWarning { + PrintToTerminal "warn" "free disk-space is getting rare - make some room for backups" +} +# prints disk space warning to 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')" + PrintToScreen "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\"}]}}}]" } -# prints disk space warning to backup log +# prints disk space warning to log function PrintToLogDiskSpaceWarning { - echo "warning: free disk-space is getting rare" >> ${backuplog} -} -# prints disk space warnig to terminal -function PrintToTerminalDiskSpaceWarning { - echo "${yellow}warning: free disk-space is getting rare${nocolor}" + PrintToLog "warn" "free disk-space is getting rare - make some room for backups" "${backuplog}" + echo "" >> "${backuplog}" } -# prints colourful not enough disk space message into screen +# prints not enough disk space to terminal +function PrintToTerminalNotEnoughDiskSpace { + PrintToTerminal "error" "not enough disk-space to perform backup-${1}" +} +# prints not enough disk space to 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')" + PrintToScreen "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\"}]}}}]" } # prints not enough disk space to backup log function PrintToLogNotEnoughDiskSpace { - echo "fatal: not enough disk-space to perform backup-${1}" >> ${backuplog} - echo "" >> ${backuplog} -} -# prints not enough disk space to terminal -function PrintToTerminalNotEnoughDiskSpace { - echo "${red}fatal: not enough disk-space to perform backup-${1}${nocolor}" + PrintToLog "error" "not enough disk-space to perform backup-${1}" "${backuplog}" + echo "" >> "${backuplog}" } -# 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')" -} -# 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 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}" + PrintToTerminal "warn" "cannot remove old backup because new backup is missing" + PrintToTerminal "warn" "could not remove old backup" + PrintToTerminal "error" "could not backup world" } - - -# 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 +# prints error messages to screen +function PrintToScreenBackupError { + PrintToScreen "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\"}]}}}]" } -# 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 backup error to log +function PrintToLogBackupError { + PrintToLog "warn" "cannot remove old backup because new backup is missing" "${backuplog}" + PrintToLog "warn" "could not remove old backup" "${backuplog}" + PrintToLog "error" "could not backup world" "${backuplog}" + echo "" >> "${backuplog}" } @@ -184,11 +213,11 @@ function CheckBackupDirectoryIntegrity { 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}" + PrintToLog "error" "the root-backupdirectory is missing - your backups are likely gone :(" "${backuplog}" + PrintToLog "info" "creating a new root-backupdirectory with name backups at ${serverdirectory}" "${backuplog}" + echo "" >> "${backuplog}" + PrintToTerminal "error" "the root-backupdirectory is missing - your backups are likely gone :(" + PrintToTerminal "info" "creating a new root-backupdirectory with name backups at ${serverdirectory}" mkdir backups fi declare -a backupcategories=( "cached" "hourly" "daily" "weekly" "monthly" ) @@ -196,11 +225,11 @@ function CheckBackupDirectoryIntegrity { for (( i = 1; i < ${arraylenght} + 1; 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} + PrintToLog "warn" "the backup-directory ${backupcategories[${i}-1]} is missing" "${backuplog}" + PrintToLog "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]}" + PrintToTerminal "warn" "the backup-directory ${backupcategories[${i}-1]} is missing" + PrintToTerminal "info" "creating ${backupdirectory}/${backupcategories[${i}-1]}" cd ${backupdirectory} mkdir ${backupcategories[${i}-1]} cd ${serverdirectory} @@ -210,20 +239,22 @@ function CheckBackupDirectoryIntegrity { # function for fetching scripts from github with error checking function FetchScriptFromGitHub { - wget --spider --quiet https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${1} + 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}" + PrintToTerminal "fatal" "Unable to connect to GitHub API. Script will exit! (maybe chose another branch?)" exit 1 else - CheckVerbose "info: fetching file: ${1} from branch ${branch} on GitHub..." - wget -q -O ${1} https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${1} + if [[ CheckVerbose ]]; then + PrintToTerminal "info" "fetching file: ${1} from branch ${branch} on GitHub..." + fi + wget -q -O "${1}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${1}" fi } # function for removing scripts from serverdirectory function RemoveScriptsFromServerDirectory { # user info about download - CheckVerbose "info: removing scripts in serverdirectory... " + PrintToTerminal "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" ) @@ -231,7 +262,9 @@ function RemoveScriptsFromServerDirectory { scriptslength=${#scripts[@]} # loop through all entries in the array for (( i = 1; i < ${scriptslength} + 1; i ++ )); do - CheckVerbose "info: removing script ${scripts[${i}-1]}" + if [[ CheckVerbose ]]; then + PrintToTerminal "info" "removing script ${scripts[${i}-1]}" + fi rm "${scripts[${i}-1]}" done } @@ -239,7 +272,7 @@ function RemoveScriptsFromServerDirectory { # function for downloading scripts from github function DownloadScriptsFromGitHub { # user info about download - CheckVerbose "info: downloading scripts from GitHub... " + PrintToTerminal "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" ) @@ -253,8 +286,6 @@ function DownloadScriptsFromGitHub { # 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" ) @@ -262,7 +293,9 @@ function MakeScriptsExecutable { 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" + if [[ CheckVerbose ]]; then + PrintToTerminal "info" "setting script ${scripts[${i}-1]} executable" + fi chmod +x ${scripts[${i}-1]} done } @@ -271,28 +304,28 @@ function MakeScriptsExecutable { function CreateSafetyBackup { # remove all older safety backups if [[ -s "${backupdirectory}/cached/safety-"* ]]; then - rm ${backupdirectory}/cached/safety-* + rm "${backupdirectory}/cached/safety-"* 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 + PrintToTerminal "action" "creating safety backup..." + 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 + # terminal output + PrintToTerminal "warn" "safety backup failed" # 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} + PrintToLog "warn" "safety backup failed" "${backuplog}" echo "" >> ${backuplog} else + # terminal output + PrintToTerminal "ok" "safety backup successful" # 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} + PrintToLog "ok" "created ${backupdirectory}/cached/safety-${newdaily}-${newhourly}.tar.gz as a safety backup" "${backuplog}" + echo "" >> "${backuplog}" fi } @@ -301,15 +334,18 @@ function CreateSafetyBackup { 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 + 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} + PrintToLog "info" "The player ${player} requested a safety backup and has permission - server will perform safety backup" "${backuplog}" + echo "" >> "${backuplog}" + # run safety backup CreateSafetyBackup + # spam protection sleep 20s 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} + PrintToLog "warn" "The player ${player} requested a safety backup and does not have permission to do so" "${backuplog}" + echo "" >> "${backuplog}" fi fi } @@ -318,27 +354,27 @@ function CheckConfirmRestartString { # check for perform restart now string 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 + 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 + PrintToLog "info" "the player ${player} requested a restart and has permission - server will restart" "${screenlog}" + ./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} + PrintToLog "warn" "the player ${player} requested a restart and does not have permission to do so" "${screenlog}" fi fi # check for perform restart string 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 + 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 + PrintToLog "info" "the player ${player} requested a restart and has permission - server will restart" "${screenlog}" + ./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} + PrintToLog "warn" "the player ${player} requested a restart and does not have permission to do so" "${screenlog}" fi fi } @@ -347,27 +383,27 @@ function CheckConfirmUpdateString { # check for perform update now string 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 + 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 + PrintToLog "info" "the player ${player} requested an update and has permission - server will update" "${screenlog}" + ./update.sh --quiet --immediately 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} + PrintToLog "warn" "the player ${player} requested an update and does not have permission to do so" "${screenlog}" fi fi # check for perform update string 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 + 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 + PrintToLog "info" "the player ${player} requested an update and has permission - server will update" "${screenlog}" + ./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} + PrintToLog "warn" "the player ${player} requested an update and does not have permission to do so" "${screenlog}" fi fi } @@ -376,27 +412,27 @@ function CheckConfirmResetString { # check for perform reset now string 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 + 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} + PrintToLog "info" "the player ${player} requested a reset and has permission - server will reset" "${screenlog}" ./reset.sh --immediately 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} + PrintToLog "warn" "the player ${player} requested a reset and does not have permission to do so" "${screenlog}" fi fi # check for perform reset string 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 + 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} + PrintToLog "info" "the player ${player} requested a reset and has permission - server will reset" "${screenlog}" ./reset.sh 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} + PrintToLog "warn" "the player ${player} requested a reset and does not have permission to do so" "${screenlog}" fi fi } From 9ef653c460a833778e197c7408466b4563abf46d Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Wed, 6 Oct 2021 17:42:08 +0200 Subject: [PATCH 002/115] restructuring whole project --- maintenance.sh | 57 ++++----------------- reset.sh | 53 ++++--------------- restart.sh | 47 +++++------------ restore.sh | 82 ++++++++---------------------- server.functions | 107 +++++++++++++++++++++++--------------- start.sh | 130 +++++++++++++++++++++++------------------------ stop.sh | 43 ++++------------ update.sh | 77 ++++++++-------------------- 8 files changed, 216 insertions(+), 380 deletions(-) diff --git a/maintenance.sh b/maintenance.sh index 0c48b46..8f8a8ba 100644 --- a/maintenance.sh +++ b/maintenance.sh @@ -56,62 +56,23 @@ if ! screen -list | grep -q "\.${servername}"; then 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 +# prints countdown to screen +PerformCountdown "going into maintenance" # 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 +PerformServerStop + +# awaits server stop +AwaitServerStop # 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 +ConditionalForceQuit # 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 +PrintToTerminal "ok" "server successfully stopped!" # 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 +CreateCachedBackup "maintenance" # log to debug if true CheckDebug "executed maintenance script" diff --git a/reset.sh b/reset.sh index 60c3eef..7efea9d 100644 --- a/reset.sh +++ b/reset.sh @@ -48,7 +48,7 @@ CheckDebug "executing reset script" ParseScriptArguments "$@" # write date to logfile -echo "action: ${date} executing reset script" >> ${screenlog} +PrintToLog "action" "${date} executing reset script" "${screenlog}" # check if server is running if ! screen -list | grep -q "\.${servername}"; then @@ -57,41 +57,17 @@ if ! screen -list | grep -q "\.${servername}"; then 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 +# prints countdown to screen +PerformCountdown "resetting the world" # 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 +PerformServerStop + +# awaits server stop +AwaitServerStop # 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 +ConditionalForceQuit # output confirmed stop echo "${green}server successfully stopped!${nocolor}" @@ -102,18 +78,7 @@ if [[ -s "${backupdirectory}/cached/reset-"* ]]; then fi # 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 +CreateCachedBackup "reset" # remove log and world echo "${red}removing world directory...${nocolor}" diff --git a/restart.sh b/restart.sh index 8c82a84..f3926d0 100644 --- a/restart.sh +++ b/restart.sh @@ -48,54 +48,31 @@ CheckDebug "executing restart script" ParseScriptArguments "$@" # write date to logfile -echo "action: ${date} executing restart script" >> ${screenlog} +PrintToLog "action" "${date} executing restart script" "${screenlog}" # 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} + PrintToTerminal "warn" "server is not currently running!" + PrintToTerminal "action" "server not running - starting server now!" + PrintToLog "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 +PerformCountdown "restarting" # 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 +PerformServerStop + +# awaits server stop +AwaitServerStop # 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 +ConditionalForceQuit # restart the server -CheckQuiet "${cyan}action: restarting server...${nocolor}" +CheckQuiet "action" "restarting server..." ./start.sh "$@" # log to debug if true diff --git a/restore.sh b/restore.sh index 55e3471..fd607a4 100644 --- a/restore.sh +++ b/restore.sh @@ -57,64 +57,26 @@ if ! screen -list | grep -q "\.${servername}"; then 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 - 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 +PerformCountdown "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 +PerformServerStop + +# awaits server stop +AwaitServerStop # 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 +ConditionalForceQuit # 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 +PrintToTerminal "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 +CreateCachedBackup "restore" # create arrays with backupdirectorys -CheckVerbose "info: scanning backup directory..." +CheckVerbose "info" "scanning backup directory..." cd ${backupdirectory} backups=($(ls)) cd hourly @@ -199,30 +161,30 @@ read -p "Continue? [Y/N]: " # if user replys yes perform restore if [[ ${REPLY} =~ ^[Yy]$ ]]; then - cd ${serverdirectory} + 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 + 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" 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 + 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 + 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} + PrintToTerminal "warn" "canceling backup restore..." + PrintToTerminal "action" "restarting server..." + PrintToLog "info" "backup restore has been canceled" "${screenlog}" + PrintToLog "info" "resuming to current live world" "${screenlog}" ./start.sh "$@" fi diff --git a/server.functions b/server.functions index 62b396c..3df6504 100644 --- a/server.functions +++ b/server.functions @@ -41,27 +41,25 @@ function ParseScriptArguments { done } - # check if verbose mode is on function CheckVerbose { if [[ ${verbose} == true ]]; then - return true + PrintToTerminal "${1}" "${2}" fi } # checks if debug mode is on function CheckDebug { if [[ ${enabledebug} == true ]]; then - return true + echo "$(date) ${1}" "debug.log" fi } # check if quiet mode is on function CheckQuiet { - if [[ ${quiet} == true ]]; then - return true + if ! [[ ${quiet} == true ]]; then + PrintToTerminal "${1}" "${2}" fi } - # prints all unpit to terminal function PrintToTerminal { if [[ $1 == "ok" ]]; then @@ -109,7 +107,6 @@ function PrintToLog { fi } - # prints success messages to terminal function PrintToTerminalBackupSuccess { PrintToTerminal "ok" "added ${backupdirectory}/hourly/${servername}-${1}.tar.gz" @@ -130,7 +127,6 @@ function PrintToLogBackupSuccess { echo "" >> "${backuplog}" } - # prints backup already exists to terminal function PrintToTerminalBackupAlreadyExists { PrintToTerminal "error" "could not create new ${1}-backup - backup already exists" @@ -145,7 +141,6 @@ function PrintToLogBackupAlreadyExists { echo "" >> "${backuplog}" } - # prints disk space warnig to terminal function PrintToTerminalDiskSpaceWarning { PrintToTerminal "warn" "free disk-space is getting rare - make some room for backups" @@ -160,7 +155,6 @@ function PrintToLogDiskSpaceWarning { echo "" >> "${backuplog}" } - # prints not enough disk space to terminal function PrintToTerminalNotEnoughDiskSpace { PrintToTerminal "error" "not enough disk-space to perform backup-${1}" @@ -175,7 +169,6 @@ function PrintToLogNotEnoughDiskSpace { echo "" >> "${backuplog}" } - # prints backup error to backup log function PrintToTerminalBackupError { PrintToTerminal "warn" "cannot remove old backup because new backup is missing" @@ -194,7 +187,6 @@ function PrintToLogBackupError { echo "" >> "${backuplog}" } - # creates a Progressbar function function ProgressBar { # process data @@ -244,9 +236,7 @@ function FetchScriptFromGitHub { PrintToTerminal "fatal" "Unable to connect to GitHub API. Script will exit! (maybe chose another branch?)" exit 1 else - if [[ CheckVerbose ]]; then - PrintToTerminal "info" "fetching file: ${1} from branch ${branch} on GitHub..." - fi + CheckVerbose "info" "fetching file: ${1} from branch ${branch} on GitHub..." wget -q -O "${1}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${1}" fi } @@ -262,9 +252,7 @@ function RemoveScriptsFromServerDirectory { scriptslength=${#scripts[@]} # loop through all entries in the array for (( i = 1; i < ${scriptslength} + 1; i ++ )); do - if [[ CheckVerbose ]]; then - PrintToTerminal "info" "removing script ${scripts[${i}-1]}" - fi + CheckVerbose "info" "removing script ${scripts[${i}-1]}" rm "${scripts[${i}-1]}" done } @@ -293,43 +281,40 @@ function MakeScriptsExecutable { scriptslength=${#scripts[@]} # loop through all entries in the array for (( i = 1; i < ${scriptslength} + 1; i ++ )); do - if [[ CheckVerbose ]]; then - PrintToTerminal "info" "setting script ${scripts[${i}-1]} executable" - fi + CheckVerbose "info" "setting script ${scripts[${i}-1]} executable" chmod +x ${scripts[${i}-1]} done } -# function for creating a safety backup -function CreateSafetyBackup { - # remove all older safety backups - if [[ -s "${backupdirectory}/cached/safety-"* ]]; then - rm "${backupdirectory}/cached/safety-"* +# function for creating a cached backup +function CreateCachedBackup { + # remove all older cached backups + if [[ -s "${backupdirectory}/cached/${1}-"* ]]; then + rm "${backupdirectory}/cached/${1}-"* fi # create backup - PrintToTerminal "action" "creating safety backup..." - tar -czf "world.tar.gz" "world" && mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/cached/safety-${newdaily}-${newhourly}.tar.gz" + PrintToTerminal "action" "creating ${1} backup..." + tar -czf "world.tar.gz" "world" && mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/cached/${1}-${newdaily}-${newhourly}.tar.gz" # check if safety backup exists - if ! [[ -s "${backupdirectory}/cached/safety-${newdaily}-${newhourly}.tar.gz" ]]; then + if ! [[ -s "${backupdirectory}/cached/${1}-${newdaily}-${newhourly}.tar.gz" ]]; then # terminal output - PrintToTerminal "warn" "safety backup failed" + PrintToTerminal "warn" "${1} backup failed" # 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\"}]}}}]" + 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/${1}-${newdaily}-${newhourly}.tar.gz does not exist\"}]}}}]" # logfile output - PrintToLog "warn" "safety backup failed" "${backuplog}" - echo "" >> ${backuplog} + PrintToLog "warn" "${1} backup failed" "${backuplog}" + echo "" >> "${backuplog}" else # terminal output - PrintToTerminal "ok" "safety backup successful" + PrintToTerminal "ok" "${1} backup successful" # 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\"}]}}}]" + 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/${1}-${newdaily}-${newhourly}.tar.gz\"}]}}}]" # logfile output - PrintToLog "ok" "created ${backupdirectory}/cached/safety-${newdaily}-${newhourly}.tar.gz as a safety backup" "${backuplog}" + PrintToLog "ok" "created ${backupdirectory}/cached/${1}-${newdaily}-${newhourly}.tar.gz as a ${1} backup" "${backuplog}" echo "" >> "${backuplog}" fi } - # check for safety backup string function CheckSafetyBackupString { if tail -1 "${screenlog}" | grep -q "perform safety backup"; then @@ -339,7 +324,7 @@ function CheckSafetyBackupString { PrintToLog "info" "The player ${player} requested a safety backup and has permission - server will perform safety backup" "${backuplog}" echo "" >> "${backuplog}" # run safety backup - CreateSafetyBackup + CreateCachedBackup "safety" # spam protection sleep 20s else @@ -415,7 +400,7 @@ function CheckConfirmResetString { if cat "ops.json" | grep -q "${player}"; then PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You successfully requested a reset of the server\"}]" PrintToLog "info" "the player ${player} requested a reset and has permission - server will reset" "${screenlog}" - ./reset.sh --immediately + ./reset.sh --quiet --now exit 0 else PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to reset the server\"}]" @@ -428,7 +413,7 @@ function CheckConfirmResetString { if cat "ops.json" | grep -q "${player}"; then PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You successfully requested a reset of the server\"}]" PrintToLog "info" "the player ${player} requested a reset and has permission - server will reset" "${screenlog}" - ./reset.sh + ./reset.sh --quiet exit 0 else PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to reset the server\"}]" @@ -437,6 +422,48 @@ function CheckConfirmResetString { fi } +# performs countdown +function PerformCountdown { + if ! [[ ${now} == true ]]; then + counter="60" + while [ ${counter} -gt 0 ]; do + if [[ "${counter}" =~ ^(60|40|20|10|5|4|3|2|1)$ ]];then + CheckQuiet "info" "server is ${1} in ${counter} seconds" + PrintToScreen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"server is ${1} in ${counter} seconds\"}]" + fi + counter=$((counter-1)) + sleep 1s + done + fi +} + +# performs a server stop +function PerformServerStop { + CheckQuiet "info" "stopping server..." + PrintToScreen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"stopping server...\"}]" + sleep 1s + PrintToScreen "stop" +} + +# awaits server stop +function AwaitServerStop { + stopchecks="0" + while [ $stopchecks -lt 30 ]; do + if ! screen -list | grep -q "\.${servername}"; then + break + fi + stopchecks=$((stopchecks+1)) + sleep 1; + done +} +# conditional force quit +function ConditionalForceQuit { + if screen -list | grep -q "${servername}"; then + PrintToTerminal "warn" "${servername} server still hasn't closed after 30 seconds, closing screen manually..." + PrintToLog "warn" "${servername} server still hasn't closed after 30 seconds, closing screen manually..." "${screenlog}" + screen -S "${servername}" -X quit + fi +} # prints game over as pixel art on terminal function PrintGameOver { diff --git a/start.sh b/start.sh index 3c6901b..aee9ce3 100644 --- a/start.sh +++ b/start.sh @@ -11,14 +11,14 @@ fi if [[ -s "server.functions" ]]; then . ./server.functions else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log + 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 "$(date) fatal: server.properties is missing" >> "fatalerror.log" echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" exit 1 fi @@ -27,7 +27,7 @@ fi if [[ -s "server.settings" ]]; then . ./server.settings else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log + echo "$(date) fatal: server.settings is missing" >> "fatalerror.log" echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" exit 1 fi @@ -36,7 +36,7 @@ fi if [ -d "${serverdirectory}" ]; then cd ${serverdirectory} else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log + echo "$(date) fatal: serverdirectory is missing" >> "fatalerror.log" echo "${red}fatal: serverdirectory is missing${nocolor}" exit 1 fi @@ -44,8 +44,8 @@ fi # 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 + echo "fatal: no executable found!" >> "${screenlog}" + echo "$(date) fatal: no executable found!" >> "fatalerror.log" exit 1 fi @@ -56,34 +56,34 @@ CheckDebug "executing start script" ParseScriptArguments "$@" # padd logfile for visibility -echo "" >> ${screenlog} -echo "" >> ${screenlog} +echo "" >> "${screenlog}" +echo "" >> "${screenlog}" # write date to logfile -echo "action: ${date} executing start script" >> ${screenlog} +PrintToLog "action" "${date} executing start script" "${screenlog}" # 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}" + PrintToTerminal "warn" "server is already running! type screen -r ${servername} to open the console" + PrintToLog "warn" "server is already running! type screen -r ${servername} to open the console" "${screenlog}" exit 1 fi # check if interface is online interfacechecks="0" while [ ${interfacechecks} -lt 8 ]; do - if ping -c 1 ${interface} &> /dev/null + if ping -c 1 "${interface}" &> /dev/null then - CheckVerbose "${green}ok: interface is online${nocolor}" - echo "ok: interface is online" >> ${screenlog} + CheckVerbose "ok" "interface is online" + PrintToLog "ok" "interface is online" "${screenlog}" break else - echo "${yellow}warning: interface is offline${nocolor}" - echo "warning: interface is offline" >> ${screenlog} + PrintToTerminal "warn" "interface is offline" + PrintToLog "warn" "interface is offline" "${screenlog}" fi if [ ${interfacechecks} -eq 7 ]; then - echo "${red}fatal: interface timed out${nocolor}" - echo "fatal: interface timed out" >> ${screenlog} + PrintToTerminal "error" "interface timed out" + PrintToLog "error" "interface timed out" "${screenlog}" fi sleep 1s interfacechecks=$((interfacechecks+1)) @@ -92,32 +92,32 @@ done # check if dnsserver is online networkchecks="0" while [ ${networkchecks} -lt 8 ]; do - if ping -c 1 ${dnsserver} &> /dev/null + if ping -c 1 "${dnsserver}" &> /dev/null then - CheckVerbose "${green}ok: nameserver is online${nocolor}" - echo "ok: nameserver is online" >> ${screenlog} + CheckVerbose "ok" "nameserver is online" + PrintToLog "ok" "nameserver is online" "${screenlog}" break else - echo "${yellow}warning: nameserver is offline${nocolor}" - echo "warning: nameserver is offline" >> ${screenlog} + PrintToTerminal "warn" "nameserver is offline${nocolor}" + PrintToLog "warn" "nameserver is offline" "${screenlog}" fi if [ ${networkchecks} -eq 7 ]; then - echo "${red}fatal: nameserver timed out${nocolor}" - echo "fatal: nameserver timed out" >> ${screenlog} + PrintToTerminal "error" "nameserver timed out" + PrintToLog "error" "nameserver timed out" "${screenlog}" fi sleep 1s networkchecks=$((networkchecks+1)) done # 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}" +CheckQuiet "info" "starting minecraft server. to view window type screen -r ${servername}." +CheckQuiet "info" "To minimise the window and let the server run in the background, press ctrl+a then ctrl+d" +PrintToLog "action" "starting ${servername} server..." "${screenlog}" +CheckVerbose "action" "starting ${servername} server..." # 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" +"${screen}" -dmSL "${servername}" -Logfile "${screenlog}" "${java}" -server "${mems}" "${memx}" "${threadcount}" -jar "${serverfile}" -nogui +"${screen}" -r "${servername}" -X colon "logfile flush 1^M" # check if screen is avaible counter="0" @@ -135,59 +135,59 @@ done # 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}" + PrintToTerminal "fatal" "something went wrong - server failed to start!" + PrintToLog "fatal" "something went wrong - server failed to start!" "${screenlog}" exit 1 fi # succesful start sequence -echo "ok: server is on startup..." >> ${screenlog} -CheckQuiet "${green}ok: server is on startup...${nocolor}" +PrintToLog "ok" "server is on startup..." "${screenlog}" +CheckQuiet "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}" + if tail "${screenlog}" | grep -q "Query running on"; then + PrintToLog "ok" "server startup successful - query up and running" "${screenlog}" + CheckQuiet "ok" "server startup successful - query 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 + PrintToTerminal "error" "server port is already in use - please change to another port" + PrintToLog "error" "server port is already in use - please change to another port" "${screenlog}" 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} + PrintToTerminal "fatal" "something went wrong - server appears to have crashed!" + PrintToTerminal "info" "crash dump - last 10 lines of ${screenlog}" + PrintToLog "fatal" "something went wrong - server appears to have crashed!" "${screenlog}" + tail -10 "${screenlog}" exit 1 fi - if tail ${screenlog} | grep -q "Preparing spawn area"; then + 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..." + CheckVerbose "info" "server is loading the environment..." fi count=$((count+1)) fi - if tail ${screenlog} | grep -q "Reloading ResourceManager"; then + if tail "${screenlog}" | grep -q "Reloading ResourceManager"; then count=$((count+1)) fi - if tail ${screenlog} | grep -q "Starting minecraft server"; then + 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..." + CheckVerbose "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}" + PrintToTerminal "warn" "the server could be crashed" + PrintToLog "warn" "the server could be crashed" "${screenlog}" exit 1 fi startupchecks=$((startupchecks+1)) @@ -195,37 +195,37 @@ while [ ${startupchecks} -lt 120 ]; do 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 "Query running on"; then + PrintToTerminal "warn" "server startup unsuccessful - perhaps query is disabled" + PrintToLog "warn" "server startup unsuccessful - perhaps query is disabled" "${screenlog}" fi # enables the watchdog script for backup integrity -if [[ ${enablewatchdog} == true ]]; then - CheckVerbose "info: activating watchdog..." +if [[ "${enablewatchdog}" == true ]]; then + CheckVerbose "info" "activating watchdog..." ./watchdog.sh & fi # check if user wants to send welcome messages -if [[ ${welcomemessage} == true ]]; then - CheckVerbose "info: activating welcome messages..." +if [[ "${welcomemessage}" == true ]]; then + CheckVerbose "info" "activating welcome messages..." ./welcome.sh & fi # check if user wants to enable task execution -if [[ ${enabletasks} == true ]]; then - CheckVerbose "info: activating task execution..." +if [[ "${enabletasks}" == true ]]; then + CheckVerbose "info" "activating task execution..." ./worker.sh & fi # if set to true change automatically to server console -if [[ ${changetoconsole} == true ]]; then - CheckVerbose "info: changing to server console..." +if [[ "${changetoconsole}" == true ]]; then + CheckVerbose "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}" +CheckQuiet "info" "if you would like to change to server console - type ${green}screen -r ${servername}" # log to debug if true CheckDebug "executed start script" diff --git a/stop.sh b/stop.sh index e9f89ae..a58ff21 100644 --- a/stop.sh +++ b/stop.sh @@ -48,7 +48,7 @@ CheckDebug "executing stop script" ParseScriptArguments "$@" # write date to logfile -echo "action: ${date} executing stop script" >> ${screenlog} +PrintToLog "action" "${date} executing stop script" "${screenlog}" # check if server is running if ! screen -list | grep -q "\.${servername}"; then @@ -57,44 +57,21 @@ if ! screen -list | grep -q "\.${servername}"; then 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 - 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 +PerformCountdown "stopping" # 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 +PerformServerStop + +# awaits server stop +AwaitServerStop # 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 +ConditionalForceQuit # output confirmed stop -echo "server successfully stopped!" >> ${screenlog} -CheckQuiet "${green}server successfully stopped!${nocolor}" +PrintToLog "ok" "server successfully stopped!" "${screenlog}" +CheckQuiet "ok" "server successfully stopped!" # log to debug if true CheckDebug "executed stop script" diff --git a/update.sh b/update.sh index 781b49b..82785a6 100644 --- a/update.sh +++ b/update.sh @@ -48,19 +48,19 @@ CheckDebug "executing update script" ParseScriptArguments "$@" # write date to logfile -echo "action: ${date} executing update script" >> ${screenlog} +PrintToLog "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-* + rm "${backupdirectory}/cached/update-"* fi # create backup CheckVerbose "${blue}backing up...${nocolor}" - tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/cached/update-${newdaily}.tar.gz + tar -czf "world.tar.gz" world && mv "${serverdirectory}/world.tar.gz ${backupdirectory}/cached/update-${newdaily}.tar.gz" # check if safety backup exists if ! [[ -s "${backupdirectory}/cached/update-${newdaily}.tar.gz" ]]; then @@ -72,7 +72,7 @@ if ! screen -list | grep -q "\.${servername}"; then fi # Test internet connectivity and update on success - wget --spider --quiet https://launcher.mojang.com/v1/objects/a16d67e5807f57fc4e550299cf20226194497dc2/server.jar + 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} @@ -84,7 +84,7 @@ if ! screen -list | grep -q "\.${servername}"; 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 + 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 @@ -96,8 +96,8 @@ if ! screen -list | grep -q "\.${servername}"; 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}" + PrintToTerminal "warn" "could not remove old serverfile ${serverfile} because new serverfile ${newserverfile} is missing" + PrintToTerminal "info" "server will startup with old serverfile ${serverfile}" fi fi fi @@ -112,66 +112,33 @@ if ! screen -list | grep -q "\.${servername}"; then MakeScriptsExecutable # restart the server - CheckQuiet "${cyan}action: restarting server...${nocolor}" + CheckQuiet "action" "restarting server..." ./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 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 +PerformCountdown "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 +PerformServerStop + +# awaits server stop +AwaitServerStop # 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 +ConditionalForceQuit # remove all older safety backups if [[ -s "${backupdirectory}/cached/update-"* ]]; then - rm ${backupdirectory}/cached/update-* + rm "${backupdirectory}/cached/update-"* fi # create backup -CheckVerbose "${blue}backing up...${nocolor}" -tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/cached/update-${newdaily}.tar.gz - -# 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 +CreateCachedBackup "update" # Test internet connectivity and update on success -wget --spider --quiet https://launcher.mojang.com/v1/objects/a16d67e5807f57fc4e550299cf20226194497dc2/server.jar +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} @@ -183,7 +150,7 @@ else 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 + 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 @@ -195,8 +162,8 @@ else 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}" + PrintToTerminal "warn" "could not remove old serverfile ${serverfile} because new serverfile ${newserverfile} is missing" + PrintToTerminal "info" "server will startup with old serverfile ${serverfile}" fi fi fi @@ -211,7 +178,7 @@ DownloadScriptsFromGitHub MakeScriptsExecutable # restart the server -CheckQuiet "${cyan}restarting server...${nocolor}" +CheckQuiet "action" "restarting server..." ./start.sh "$@" # log to debug if true From 6302330de962215b47ae9a00ac74558ae5874f8d Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Wed, 6 Oct 2021 17:56:25 +0200 Subject: [PATCH 003/115] minor fixes --- restart.sh | 4 ++++ restore.sh | 3 ++- server.functions | 2 +- update.sh | 7 +++---- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/restart.sh b/restart.sh index f3926d0..1d4d7ae 100644 --- a/restart.sh +++ b/restart.sh @@ -71,6 +71,10 @@ AwaitServerStop # force quit server if not stopped ConditionalForceQuit +# output confirmed stop +PrintToLog "ok" "server successfully stopped!" "${screenlog}" +CheckQuiet "ok" "server successfully stopped!" + # restart the server CheckQuiet "action" "restarting server..." ./start.sh "$@" diff --git a/restore.sh b/restore.sh index fd607a4..5abf280 100644 --- a/restore.sh +++ b/restore.sh @@ -70,7 +70,8 @@ AwaitServerStop ConditionalForceQuit # output confirmed stop -PrintToTerminal "ok" "server successfully stopped!" +PrintToLog "ok" "server successfully stopped!" "${screenlog}" +CheckQuiet "ok" "server successfully stopped!" # create backup CreateCachedBackup "restore" diff --git a/server.functions b/server.functions index 3df6504..4278fc4 100644 --- a/server.functions +++ b/server.functions @@ -439,7 +439,7 @@ function PerformCountdown { # performs a server stop function PerformServerStop { - CheckQuiet "info" "stopping server..." + CheckQuiet "action" "stopping server..." PrintToScreen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"stopping server...\"}]" sleep 1s PrintToScreen "stop" diff --git a/update.sh b/update.sh index 82785a6..05785a7 100644 --- a/update.sh +++ b/update.sh @@ -129,10 +129,9 @@ AwaitServerStop # force quit server if not stopped ConditionalForceQuit -# remove all older safety backups -if [[ -s "${backupdirectory}/cached/update-"* ]]; then - rm "${backupdirectory}/cached/update-"* -fi +# output confirmed stop +PrintToLog "ok" "server successfully stopped!" "${screenlog}" +CheckQuiet "ok" "server successfully stopped!" # create backup CreateCachedBackup "update" From 1b07da9860b11697fa9ea84ffe2c364fac948f48 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 7 Oct 2021 22:09:20 +0200 Subject: [PATCH 004/115] improved handling of spaces in file names --- backup.sh | 152 ++++++++++++++++++++++++++++++----------------- server.functions | 10 +++- start.sh | 8 +-- 3 files changed, 107 insertions(+), 63 deletions(-) diff --git a/backup.sh b/backup.sh index b9225a5..d441333 100644 --- a/backup.sh +++ b/backup.sh @@ -21,14 +21,14 @@ fi if [[ -s "server.functions" ]]; then . ./server.functions else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log + 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 "$(date) fatal: server.properties is missing" >> "fatalerror.log" echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" exit 1 fi @@ -37,7 +37,7 @@ fi if [[ -s "server.settings" ]]; then . ./server.settings else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log + echo "$(date) fatal: server.settings is missing" >> "fatalerror.log" echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" exit 1 fi @@ -46,7 +46,7 @@ fi if [ -d "${serverdirectory}" ]; then cd ${serverdirectory} else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log + echo "$(date) fatal: serverdirectory is missing" >> "fatalerror.log" echo "${red}fatal: serverdirectory is missing${nocolor}" exit 1 fi @@ -62,8 +62,8 @@ CheckBackupDirectoryIntegrity if [ ${dohourly} = true ]; then # write date and execute into logfiles - echo "action: ${date} executing backup-hourly script" >> ${screenlog} - echo "action: ${date} executing backup-hourly script" >> ${backuplog} + PrintToLog "action" "${date} executing backup-hourly script" "${screenlog}" + PrintToLog "action" "${date} executing backup-hourly script" "${backuplog}" CheckDebug "executing backup-hourly script" # start milliseconds timer @@ -71,10 +71,10 @@ if [ ${dohourly} = true ]; then # 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} + PrintToTerminal "warn" "server is not currently running!" + PrintToLog "info" "server is not currently running!" "${screenlog}" + PrintToLog "info" "server is not currently running!" "${backuplog}" + echo "" >> "${backuplog}" exit 1 fi @@ -99,15 +99,25 @@ if [ ${dohourly} = true ]; then # 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 + rm "world.tar.gz" fi + # disable auto save PrintToScreen "save-off" - tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/hourly/${servername}-${newhourly}.tar.gz + # run backup with compression + cp -r "world" "tmp" + tar -czf "world.tar.gz" "tmp" + # check for tar errors + if [ "$?" != 0 ]; then + CheckDebug "backup script reports tar error while performing backup-hourly" + fi + mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/hourly/${servername}-${newhourly}.tar.gz" + rm -r "tmp" + # enable auto save PrintToScreen "save-on" else + PrintToTerminalBackupAlreadyExists "hourly" PrintToScreenBackupAlreadyExists "${newhourly}" "${oldhourly}" PrintToLogBackupAlreadyExists "hourly" - PrintToTerminalBackupAlreadyExists "hourly" CheckDebug "backup script reports backup already exists while performing backup-hourly" exit 1 fi @@ -116,7 +126,7 @@ if [ ${dohourly} = true ]; then 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 + rm "${backupdirectory}/hourly/${servername}-${oldhourly}.tar.gz" fi # stop milliseconds timer after=$(date +%s%3N) @@ -141,9 +151,9 @@ if [ ${dohourly} = true ]; then else # write to logfiles that it's disabled - CheckDebug "info: backup-hourly is disabled" - echo "info: backup-hourly is disabled" >> ${backuplog} - echo "" >> ${backuplog} + CheckDebug "backup-hourly is disabled" + PrintToLog "info" "backup-hourly is disabled" "${backuplog}" + echo "" >> "${backuplog}" fi @@ -151,8 +161,8 @@ fi 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} + PrintToLog "action" "${date} executing backup-daily script" "${screenlog}" + PrintToLog "action" "${date} executing backup-daily script" "${backuplog}" CheckDebug "executing backup-daily script" # check if daily backups are anabled @@ -163,10 +173,10 @@ if [ ${hours} -eq ${dailybackuptime} ]; then # 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} + PrintToTerminal "warn" "server is not currently running!" + PrintToLog "info" "server is not currently running!" "${screenlog}" + PrintToLog "info" "server is not currently running!" "${backuplog}" + echo "" >> "${backuplog}" exit 1 fi @@ -191,15 +201,25 @@ if [ ${hours} -eq ${dailybackuptime} ]; then # 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 + rm "world.tar.gz" fi + # disable auto save PrintToScreen "save-off" - tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/daily/${servername}-${newdaily}.tar.gz + # run backup with compression + cp -r "world" "tmp" + tar -czf "world.tar.gz" "tmp" + # check for tar errors + if [ "$?" != 0 ]; then + CheckDebug "backup script reports tar error while performing backup-daily" + fi + mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/daily/${servername}-${newdaily}.tar.gz" + rm -r "tmp" + # enable auto save PrintToScreen "save-on" else + PrintToTerminalBackupAlreadyExists "daily" PrintToScreenBackupAlreadyExists "${newdaily}" "${olddaily}" PrintToLogBackupAlreadyExists "daily" - PrintToTerminalBackupAlreadyExists "daily" CheckDebug "backup script reports backup already exists while performing backup-daily" exit 1 fi @@ -208,7 +228,7 @@ if [ ${hours} -eq ${dailybackuptime} ]; then 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 + rm "${backupdirectory}/daily/${servername}-${olddaily}.tar.gz" fi # stop milliseconds timer after=$(date +%s%3N) @@ -233,9 +253,9 @@ if [ ${hours} -eq ${dailybackuptime} ]; then else # write to logfiles that it's disabled - CheckDebug "info: backup-daily is disabled" - echo "info: backup-daily is disabled" >> ${backuplog} - echo "" >> ${backuplog} + CheckDebug "backup-daily is disabled" + PrintToLog "info" "backup-daily is disabled" "${backuplog}" + echo "" >> "${backuplog}" fi fi @@ -244,8 +264,8 @@ fi 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} + PrintToLog "action" "${date} executing backup-weekly script" "${screenlog}" + PrintToLog "action" "${date} executing backup-weekly script" "${backuplog}" CheckDebug "executing backup-weekly script" # check if weekly backups are enabled @@ -256,10 +276,10 @@ if [ ${hours} -eq ${dailybackuptime} ] && [ ${weekday} -eq ${weeklybackupday} ]; # 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} + PrintToTerminal "warn" "server is not currently running!" + PrintToLog "info" "server is not currently running!" "${screenlog}" + PrintToLog "info" "server is not currently running!" "${backuplog}" + echo "" >> "${backuplog}" exit 1 fi @@ -284,15 +304,25 @@ if [ ${hours} -eq ${dailybackuptime} ] && [ ${weekday} -eq ${weeklybackupday} ]; # 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 + rm "world.tar.gz" fi + # disable auto save PrintToScreen "save-off" - tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/weekly/${servername}-${newweekly}.tar.gz + # run backup with compression + cp -r "world" "tmp" + tar -czf "world.tar.gz" "tmp" + # check for tar errors + if [ "$?" != 0 ]; then + CheckDebug "backup script reports tar error while performing backup-weekly" + fi + mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/weekly/${servername}-${newweekly}.tar.gz" + rm -r "tmp" + # enable auto save PrintToScreen "save-on" else + PrintToTerminalBackupAlreadyExists "weekly" PrintToScreenBackupAlreadyExists "${newweekly}" "${oldweekly}" PrintToLogBackupAlreadyExists "weekly" - PrintToTerminalBackupAlreadyExists "weekly" CheckDebug "backup script reports backup already exists while performing backup-weekly" exit 1 fi @@ -301,7 +331,7 @@ if [ ${hours} -eq ${dailybackuptime} ] && [ ${weekday} -eq ${weeklybackupday} ]; 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 + rm "${backupdirectory}/weekly/${servername}-${oldweekly}.tar.gz" fi # stop milliseconds timer after=$(date +%s%3N) @@ -326,9 +356,9 @@ if [ ${hours} -eq ${dailybackuptime} ] && [ ${weekday} -eq ${weeklybackupday} ]; else # write to logfiles that it's disabled - CheckDebug "info: backup-weekly is disabled" - echo "info: backup-weekly is disabled" >> ${backuplog} - echo "" >> ${backuplog} + CheckDebug "backup-weekly is disabled" + PrintToLog "info" "backup-weekly is disabled" "${backuplog}" + echo "" >> "${backuplog}" fi fi @@ -337,8 +367,8 @@ fi 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} + PrintToLog "action" "${date} executing backup-monthly script" "${screenlog}" + PrintToLog "action" "${date} executing backup-monthly script" "${backuplog}" CheckDebug "executing backup-monthly script" # check if monthly backups are enabled @@ -349,10 +379,10 @@ if [ ${hours} -eq ${dailybackuptime} ] && [ ${dayofmonth} -eq ${monthlybackupday # 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} + PrintToTerminal "warn" "server is not currently running!" + PrintToLog "info" "server is not currently running!" "${screenlog}" + PrintToLog "info" "server is not currently running!" "${backuplog}" + echo "" >> "${backuplog}" exit 1 fi @@ -377,15 +407,25 @@ if [ ${hours} -eq ${dailybackuptime} ] && [ ${dayofmonth} -eq ${monthlybackupday # 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 + rm "world.tar.gz" fi + # disable auto save PrintToScreen "save-off" - tar -czf world.tar.gz world && mv ${serverdirectory}/world.tar.gz ${backupdirectory}/monthly/${servername}-${newmonthly}.tar.gz + # run backup with compression + cp -r "world" "tmp" + tar -czf "world.tar.gz" "tmp" + # check for tar errors + if [ "$?" != 0 ]; then + CheckDebug "backup script reports tar error while performing backup-monthly" + fi + mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/monthly/${servername}-${newmonthly}.tar.gz" + rm -r "tmp" + # enable auto save PrintToScreen "save-on" else + PrintToTerminalBackupAlreadyExists "monthly" PrintToScreenBackupAlreadyExists "${newmonthly}" "${oldmonthly}" PrintToLogBackupAlreadyExists "monthly" - PrintToTerminalBackupAlreadyExists "monthly" CheckDebug "backup script reports backup already exists while performing backup-monthly" exit 1 fi @@ -394,7 +434,7 @@ if [ ${hours} -eq ${dailybackuptime} ] && [ ${dayofmonth} -eq ${monthlybackupday 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 + rm "${backupdirectory}/monthly/${servername}-${oldmonthly}.tar.gz" fi # stop milliseconds timer after=$(date +%s%3N) @@ -419,9 +459,9 @@ if [ ${hours} -eq ${dailybackuptime} ] && [ ${dayofmonth} -eq ${monthlybackupday else # write to logfiles that it's disabled - CheckDebug "info: backup-monthly is disabled" - echo "info: backup-monthly is disabled" >> ${backuplog} - echo "" >> ${backuplog} + CheckDebug "backup-monthly is disabled" + PrintToLog "info" "backup-monthly is disabled" "${backuplog}" + echo "" >> "${backuplog}" fi fi diff --git a/server.functions b/server.functions index 4278fc4..a6bbd5f 100644 --- a/server.functions +++ b/server.functions @@ -219,7 +219,7 @@ function CheckBackupDirectoryIntegrity { if ! ls ${backupdirectory}/${backupcategories[${i}-1]} &> /dev/null; then PrintToLog "warn" "the backup-directory ${backupcategories[${i}-1]} is missing" "${backuplog}" PrintToLog "info" "creating ${backupdirectory}/${backupcategories[${i}-1]}" "${backuplog}" - echo "" >> ${backuplog} + echo "" >> "${backuplog}" PrintToTerminal "warn" "the backup-directory ${backupcategories[${i}-1]} is missing" PrintToTerminal "info" "creating ${backupdirectory}/${backupcategories[${i}-1]}" cd ${backupdirectory} @@ -300,7 +300,9 @@ function CreateCachedBackup { # terminal output PrintToTerminal "warn" "${1} backup failed" # 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/${1}-${newdaily}-${newhourly}.tar.gz does not exist\"}]}}}]" + if ! screen -list | grep -q "\.${servername}"; then + 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/${1}-${newdaily}-${newhourly}.tar.gz does not exist\"}]}}}]" + fi # logfile output PrintToLog "warn" "${1} backup failed" "${backuplog}" echo "" >> "${backuplog}" @@ -308,7 +310,9 @@ function CreateCachedBackup { # terminal output PrintToTerminal "ok" "${1} backup successful" # 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/${1}-${newdaily}-${newhourly}.tar.gz\"}]}}}]" + if ! screen -list | grep -q "\.${servername}"; then + 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/${1}-${newdaily}-${newhourly}.tar.gz\"}]}}}]" + fi # logfile output PrintToLog "ok" "created ${backupdirectory}/cached/${1}-${newdaily}-${newhourly}.tar.gz as a ${1} backup" "${backuplog}" echo "" >> "${backuplog}" diff --git a/start.sh b/start.sh index aee9ce3..3eee3e3 100644 --- a/start.sh +++ b/start.sh @@ -111,7 +111,7 @@ done # user information CheckQuiet "info" "starting minecraft server. to view window type screen -r ${servername}." -CheckQuiet "info" "To minimise the window and let the server run in the background, press ctrl+a then ctrl+d" +CheckQuiet "info" "to minimise the window and let the server run in the background, press ctrl+a then ctrl+d" PrintToLog "action" "starting ${servername} server..." "${screenlog}" CheckVerbose "action" "starting ${servername} server..." @@ -149,7 +149,7 @@ count="0" counter="0" startupchecks="0" while [ ${startupchecks} -lt 120 ]; do - if tail "${screenlog}" | grep -q "Query running on"; then + if tail "${screenlog}" | grep -q "Thread Query Listener started"; then PrintToLog "ok" "server startup successful - query up and running" "${screenlog}" CheckQuiet "ok" "server startup successful - query up and running" break @@ -195,7 +195,7 @@ while [ ${startupchecks} -lt 120 ]; do done # check if screenlog does not contain startup confirmation -if ! tail "${screenlog}" | grep -q "Query running on"; then +if ! tail "${screenlog}" | grep -q "Thread Query Listener started"; then PrintToTerminal "warn" "server startup unsuccessful - perhaps query is disabled" PrintToLog "warn" "server startup unsuccessful - perhaps query is disabled" "${screenlog}" fi @@ -225,7 +225,7 @@ if [[ "${changetoconsole}" == true ]]; then fi # user information -CheckQuiet "info" "if you would like to change to server console - type ${green}screen -r ${servername}" +CheckQuiet "info" "if you would like to change to server console - type screen -r ${servername}" # log to debug if true CheckDebug "executed start script" From aa9d14f2af28fcb33be2933a89b56293e3695790 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 7 Oct 2021 22:19:56 +0200 Subject: [PATCH 005/115] spelling corrections --- README.md | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 3e7adf8..ea8bbef 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ 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. @@ -11,16 +11,16 @@ sudo apt install openjdk-17-jre-headless iputils-ping net-tools mailutils coreut ``` ## setup Then, you can download and execute the setup script.
-This command downloads, makes exectable and executes the setup script. +This command downloads, makes executable 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 pre-filled 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. +Screen is an amazing command line tool that creates a "virtual" terminal inside your terminal. You can view all your active screens by typing: `screen -list`
@@ -43,8 +43,8 @@ I will explain some of them to you. `tp ${playername} ${x} ${y} ${z}` teleporting a player to cords.
`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. +Important: If you do these commands in-game you will need to put a `/` before each 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. @@ -56,7 +56,7 @@ 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 @@ -72,25 +72,25 @@ 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 costomize 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)
+`max-players=` (limits the maximum 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)
+`view-distance=` (defines number of in-game chunks 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)
+`server-port=` (default by 25565. Only important 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]
+`spawn-protection=` (the number of block at the world-spawn only operators can touch)
+`pvp=` (ability for player to do damage to eachother) [true/false]
`enable-command-block=` (enables command blocks to tinker with) [true/false]
## scripts @@ -102,7 +102,9 @@ There are lots of script in your ${serverdirectory}. Normally, the executable on Example: `./start.sh -v` -Arguments: `-i --immediately -q --quiet -v --verbose` +Example: `./start.sh -q` + +Arguments: `-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. @@ -122,13 +124,13 @@ 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 +* * * * * cd ${serverdirectory} && ${serverdirectory}/${script}.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: ``` From cce7fc9eb8f0b00301f6eb903702167366365ae7 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 7 Oct 2021 22:52:30 +0200 Subject: [PATCH 006/115] better pre-rendering --- prerender.sh | 165 +++++++++++++++++---------------------------------- 1 file changed, 56 insertions(+), 109 deletions(-) diff --git a/prerender.sh b/prerender.sh index 9837516..89b793a 100644 --- a/prerender.sh +++ b/prerender.sh @@ -11,14 +11,14 @@ fi if [[ -s "server.functions" ]]; then . ./server.functions else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log + 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 "$(date) fatal: server.properties is missing" >> "fatalerror.log" echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" exit 1 fi @@ -27,7 +27,7 @@ fi if [[ -s "server.settings" ]]; then . ./server.settings else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log + echo "$(date) fatal: server.settings is missing" >> "fatalerror.log" echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" exit 1 fi @@ -36,42 +36,42 @@ fi if [ -d "${serverdirectory}" ]; then cd ${serverdirectory} else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log + 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" +CheckDebug "executing pre-render 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}" + PrintToTerminal "warn" "server is not currently running!" exit 1 fi # let user chose between online and offline prerendering -echo "Would you like to startup online or offline prerendering?" -PS3="Your choice: " +echo "would you like to startup online or offline pre-rendering?" +PS3="your choice: " method=("online" "offline") select method in "${method[@]}"; do case $method in "online") - echo "action ${cyan}starting online prerenderer...${nocolor}" + PrintToTerminal "action" "starting online pre-renderer..." # 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}" + PrintToTerminal "info" "i will pre-render your minecraft world by teleporting a selected player through it" + PrintToTerminal "info" "i will scan so to speak in a grid with the spacing of 256 blocks" # ask for playername - read -p "Please enter a playername: " playername - echo "The player will be ${green}${playername}${nocolor}" + read -p "please enter a player-name: " playername + echo "the player will be ${green}${playername}${nocolor}" # ask for cords - PS3="Which radius would you like to prerender? " + PS3="which radius would you like to pre-render? " grid=("1024*1024" "2048*2048" "4096*4096" "8192*8192") select grid in "${grid[@]}"; do case $grid in @@ -103,18 +103,18 @@ select method in "${method[@]}"; do amount="65" break ;; - *) echo "Please choose an option from the list: " ;; + *) 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}" + PrintToTerminal "info" "i would like to know how fast you want to scan your world" + PrintToTerminal "info" "i would recommend an interval of 20 to 80 seconds depending on your server resources" + PrintToTerminal "info" "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 + read -p "please enter an interval between 8 and 128 seconds: " interval done # calculate some internal intervals @@ -122,27 +122,27 @@ select method in "${method[@]}"; do 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}" + PrintToTerminal "info" "the selected grid will be ${green}${area}${nocolor}" + PrintToTerminal "info" "the selected interval will be ${green}${interval}${nocolor}" + PrintToTerminal "info" "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" + echo "It will take about ${estimated} seconds to finish pre-rendering" 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}" + then echo "${green}starting pre-renderer...${nocolor}" else echo "${red}exiting...${nocolor}" exit 1 fi # prerender start - echo "Prerendering started" - echo "Progress: [0/$((${amount} * ${amount}))]" + echo "pre-rendering started" + echo "progress: [0/$((${amount} * ${amount}))]" sleep 2s # teleport script with progress @@ -156,37 +156,38 @@ select method in "${method[@]}"; do # progress counter ProgressBar "${blue}[Script]${nocolor} Progress: [${progress}/${totalamount}]" "${progress}" "${totalamount}" # teleporting with facing directions - PrintToScreen "tp ${playername} ${x} ${y} ${z} 0 0" + PrintToScreen "tp ${playername} ${x} ~ ${z} 0 0" ${between} - PrintToScreen "tp ${playername} ${x} ${y} ${z} 90 0" + PrintToScreen "tp ${playername} ${x} ~ ${z} 90 0" ${between} - PrintToScreen "tp ${playername} ${x} ${y} ${z} 180 0" + PrintToScreen "tp ${playername} ${x} ~ ${z} 180 0" ${between} - PrintToScreen "tp ${playername} ${x} ${y} ${z} 270 0" + PrintToScreen "tp ${playername} ${x} ~ ${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}" + PrintToScreen "say pre-rendering of your world has finished" + + # user info + PrintToTerminal "info" "pre-rendering of your world has finished" + PrintToTerminal "info" "rendered ${totalblocks} [${area}] blocks of area" # kick player with finished message - screen -Rd ${servername} -X stuff "kick ${playername} prerendering of your world has finished$(printf '\r')" + PrintToScreen "kick ${playername} pre-rendering of your world has finished" ;; "offline") - echo "${magenta}starting offline prerenderer...${nocolor}" + PrintToTerminal "action" "starting offline pre-renderer..." # 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}" + PrintToTerminal "info" "i will pre-render your minecraft world by setting the world-spawn to various coordinates and then restarting the server over and over" + PrintToTerminal "info" "i will scan so to speak in a grid with the spacing of 256 blocks" # ask for cords - PS3="Which radius would you like to prerender? " + PS3="Which radius would you like to pre-render? " grid=("1024*1024" "2048*2048" "4096*4096" "8192*8192") select grid in "${grid[@]}"; do case $grid in @@ -218,13 +219,13 @@ select method in "${method[@]}"; do amount="65" break ;; - *) echo "Please choose an option from the list: " ;; + *) 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 "I would recommend an interval of 20 to 80 seconds depending on your server resources" 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])$" @@ -234,24 +235,24 @@ select method in "${method[@]}"; do interval="sleep ${interval}s" # ask for permission to proceed - echo "I will now start to prerender your world using worldspawns and server restart" + echo "I will now start to pre-render your world using world-spawns 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}" + then echo "${green}starting pre-renderer...${nocolor}" else echo "${red}exiting...${nocolor}" exit 1 fi # prerender start - echo "Prerendering started" - echo "Progress: [0/$((${amount} * ${amount}))]" + PrintToterminal "info" "pre-rendering started" sleep 2s # teleport script with progress + totalamount=$((${amount} * ${amount})) progress="1" counting="1" y="120" @@ -259,83 +260,29 @@ select method in "${method[@]}"; do for z in "${cords[@]}"; do let "progress=counting" # progress counter - echo "${blue}[Script]${nocolor} Progress: [${progress}/$((${amount} * ${amount}))]" + ProgressBar "${blue}[Script]${nocolor} Progress: [${progress}/${totalamount}]" "${progress}" "${totalamount}" + # stop server + ./stop --quiet --now # 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} + PrintToScreen "setworldspawn ${x} ~ ${z}" + # start server + ./start --quiet done done # reset spawnpoint - PrintToScreen "setworldspawn 0 100 0" + PrintToScreen "setworldspawn 0 ~ 0" # command line info - echo "${green}Prerendering of your world has finished${nocolor}" + PrintToTerminal "ok" "prerendering of your world has finished" ;; - *) echo "Please choose an option from the list: " ;; + *) echo "please choose an option from the list: " ;; esac done # log to debug if true -CheckDebug "executed prerender script" +CheckDebug "executed pre-render script" # exit with code 0 exit 0 From e2dc89e0e899d2c1c2dfa1ffb66adbf9f6a42f8c Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 7 Oct 2021 22:57:32 +0200 Subject: [PATCH 007/115] bugfixes --- prerender.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/prerender.sh b/prerender.sh index 89b793a..26e4fcd 100644 --- a/prerender.sh +++ b/prerender.sh @@ -262,11 +262,11 @@ select method in "${method[@]}"; do # progress counter ProgressBar "${blue}[Script]${nocolor} Progress: [${progress}/${totalamount}]" "${progress}" "${totalamount}" # stop server - ./stop --quiet --now + ./stop.sh --quiet --now # setworldspawn to x y z PrintToScreen "setworldspawn ${x} ~ ${z}" # start server - ./start --quiet + ./start.sh --quiet done done From e377861c25d12c7b3050aab6594d0f56110c35a6 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 7 Oct 2021 22:59:13 +0200 Subject: [PATCH 008/115] more bugfixes --- prerender.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/prerender.sh b/prerender.sh index 26e4fcd..b6143c7 100644 --- a/prerender.sh +++ b/prerender.sh @@ -177,7 +177,7 @@ select method in "${method[@]}"; do # kick player with finished message PrintToScreen "kick ${playername} pre-rendering of your world has finished" - + break ;; "offline") PrintToTerminal "action" "starting offline pre-renderer..." @@ -274,8 +274,8 @@ select method in "${method[@]}"; do PrintToScreen "setworldspawn 0 ~ 0" # command line info - PrintToTerminal "ok" "prerendering of your world has finished" - + PrintToTerminal "ok" "pre-rendering of your world has finished" + break ;; *) echo "please choose an option from the list: " ;; esac From 497d878178d960229a75af886b828d224c3a3b9b Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 7 Oct 2021 23:04:01 +0200 Subject: [PATCH 009/115] fixed offline pre-redering --- prerender.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/prerender.sh b/prerender.sh index b6143c7..4b49491 100644 --- a/prerender.sh +++ b/prerender.sh @@ -248,7 +248,7 @@ select method in "${method[@]}"; do fi # prerender start - PrintToterminal "info" "pre-rendering started" + PrintToTerminal "info" "pre-rendering started" sleep 2s # teleport script with progress @@ -261,10 +261,10 @@ select method in "${method[@]}"; do let "progress=counting" # progress counter ProgressBar "${blue}[Script]${nocolor} Progress: [${progress}/${totalamount}]" "${progress}" "${totalamount}" - # stop server - ./stop.sh --quiet --now # setworldspawn to x y z PrintToScreen "setworldspawn ${x} ~ ${z}" + # stop server + ./stop.sh --quiet --now # start server ./start.sh --quiet done From 5cc90500c9a9a27b187fc8f71a680e504c41c154 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 7 Oct 2021 23:17:08 +0200 Subject: [PATCH 010/115] simplified update process --- update.sh | 125 ++++++++++++++---------------------------------------- 1 file changed, 31 insertions(+), 94 deletions(-) diff --git a/update.sh b/update.sh index 05785a7..18a0e8a 100644 --- a/update.sh +++ b/update.sh @@ -11,14 +11,14 @@ fi if [[ -s "server.functions" ]]; then . ./server.functions else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log + 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 "$(date) fatal: server.properties is missing" >> "fatalerror.log" echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" exit 1 fi @@ -27,7 +27,7 @@ fi if [[ -s "server.settings" ]]; then . ./server.settings else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log + echo "$(date) fatal: server.settings is missing" >> "fatalerror.log" echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" exit 1 fi @@ -36,7 +36,7 @@ fi if [ -d "${serverdirectory}" ]; then cd ${serverdirectory} else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log + echo "$(date) fatal: serverdirectory is missing" >> "fatalerror.log" echo "${red}fatal: serverdirectory is missing${nocolor}" exit 1 fi @@ -51,118 +51,55 @@ ParseScriptArguments "$@" PrintToLog "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 - - # create backup - CheckVerbose "${blue}backing up...${nocolor}" - tar -czf "world.tar.gz" world && mv "${serverdirectory}/world.tar.gz ${backupdirectory}/cached/update-${newdaily}.tar.gz" - - # 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 - PrintToTerminal "warn" "could not remove old serverfile ${serverfile} because new serverfile ${newserverfile} is missing" - PrintToTerminal "info" "server will startup with old serverfile ${serverfile}" - fi - fi - fi - - # remove scripts from serverdirectory - RemoveScriptsFromServerDirectory - - # downloading scripts from github - DownloadScriptsFromGitHub - - # make selected scripts executable - MakeScriptsExecutable - - # restart the server - CheckQuiet "action" "restarting server..." - ./start.sh "$@" - exit 0 +if screen -list | grep -q "\.${servername}"; then + + # prints countdown to screen + PerformCountdown "updating" + + # server stop + PerformServerStop + + # awaits server stop + AwaitServerStop + + # force quit server if not stopped + ConditionalForceQuit + + # output confirmed stop + PrintToLog "ok" "server successfully stopped!" "${screenlog}" + CheckQuiet "ok" "server successfully stopped!" fi -# prints countdown to screen -PerformCountdown "updating" - -# server stop -PerformServerStop - -# awaits server stop -AwaitServerStop - -# force quit server if not stopped -ConditionalForceQuit - -# output confirmed stop -PrintToLog "ok" "server successfully stopped!" "${screenlog}" -CheckQuiet "ok" "server successfully stopped!" - # create backup CreateCachedBackup "update" # 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} + PrintToTerminal "warn" "unable to connect to mojang api skipping update..." + PrintToLog "warn" "unable to connect to mojang api skipping update..." "${screenlog}" else - CheckQuiet "${green}downloading newest server version...${nocolor}" - echo "downloading newest server version..." >> ${screenlog} + CheckQuiet "ok" "downloading newest server version..." + PrintToLog "info" "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} + CheckVerbose "info" "you are running the newest server version - skipping update" + PrintToLog "info" "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 + CheckVerbose "ok" "updating server.settings for startup with new server version 1.17.1" + sed -i "s|${serverfile}|${newserverfile}|g" "server.settings" # remove old serverfile if it exists if [ -f "${serverfile}" ]; then rm ${serverfile} fi else - PrintToTerminal "warn" "could not remove old serverfile ${serverfile} because new serverfile ${newserverfile} is missing" - PrintToTerminal "info" "server will startup with old serverfile ${serverfile}" + PrintToTerminal "warn" "could not remove old server-file ${serverfile} because new server-file ${newserverfile} is missing" + CheckQuiet "info" "server will startup with old server-file ${serverfile}" fi fi fi From e05ca2c317fcbd751ac1f2d38aef894460dd972e Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 7 Oct 2021 23:23:23 +0200 Subject: [PATCH 011/115] check if screen exists before printing to screen --- server.functions | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/server.functions b/server.functions index a6bbd5f..c75ec5b 100644 --- a/server.functions +++ b/server.functions @@ -83,7 +83,9 @@ function PrintToTerminal { } # prints all input to screen function PrintToScreen { - screen -Rd ${servername} -X stuff "${1}$(printf '\r')" + if screen -list | grep -q "\.${servername}"; then + screen -Rd "${servername}" -X stuff "${1}$(printf '\r')" + fi } # prints all input to log function PrintToLog { @@ -300,9 +302,7 @@ function CreateCachedBackup { # terminal output PrintToTerminal "warn" "${1} backup failed" # ingame output - if ! screen -list | grep -q "\.${servername}"; then - 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/${1}-${newdaily}-${newhourly}.tar.gz does not exist\"}]}}}]" - fi + 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/${1}-${newdaily}-${newhourly}.tar.gz does not exist\"}]}}}]" # logfile output PrintToLog "warn" "${1} backup failed" "${backuplog}" echo "" >> "${backuplog}" @@ -310,9 +310,7 @@ function CreateCachedBackup { # terminal output PrintToTerminal "ok" "${1} backup successful" # ingame output - if ! screen -list | grep -q "\.${servername}"; then - 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/${1}-${newdaily}-${newhourly}.tar.gz\"}]}}}]" - fi + 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/${1}-${newdaily}-${newhourly}.tar.gz\"}]}}}]" # logfile output PrintToLog "ok" "created ${backupdirectory}/cached/${1}-${newdaily}-${newhourly}.tar.gz as a ${1} backup" "${backuplog}" echo "" >> "${backuplog}" From c3bc72a79cd67b8a61cac72f375b171cc864e8dd Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 9 Oct 2021 20:44:09 +0200 Subject: [PATCH 012/115] some quiet fixes --- server.functions | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/server.functions b/server.functions index c75ec5b..42448b8 100644 --- a/server.functions +++ b/server.functions @@ -246,7 +246,7 @@ fi # function for removing scripts from serverdirectory function RemoveScriptsFromServerDirectory { # user info about download - PrintToTerminal "info" "removing scripts in serverdirectory..." + 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" ) @@ -262,7 +262,7 @@ function RemoveScriptsFromServerDirectory { # function for downloading scripts from github function DownloadScriptsFromGitHub { # user info about download - PrintToTerminal "info" "downloading scripts from GitHub..." + 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" ) @@ -295,7 +295,7 @@ function CreateCachedBackup { rm "${backupdirectory}/cached/${1}-"* fi # create backup - PrintToTerminal "action" "creating ${1} backup..." + CheckQuiet "action" "creating ${1} backup..." tar -czf "world.tar.gz" "world" && mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/cached/${1}-${newdaily}-${newhourly}.tar.gz" # check if safety backup exists if ! [[ -s "${backupdirectory}/cached/${1}-${newdaily}-${newhourly}.tar.gz" ]]; then @@ -308,7 +308,7 @@ function CreateCachedBackup { echo "" >> "${backuplog}" else # terminal output - PrintToTerminal "ok" "${1} backup successful" + CheckQuiet "ok" "${1} backup successful" # 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/${1}-${newdaily}-${newhourly}.tar.gz\"}]}}}]" # logfile output From 78a196e9befd781ed79285d1e1b2611796c7fb12 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 9 Oct 2021 20:57:37 +0200 Subject: [PATCH 013/115] simplified venting --- vent.sh | 108 +++++++++++++++++++------------------------------------- 1 file changed, 36 insertions(+), 72 deletions(-) diff --git a/vent.sh b/vent.sh index 38e2356..2a676e4 100644 --- a/vent.sh +++ b/vent.sh @@ -13,14 +13,14 @@ fi if [[ -s "server.functions" ]]; then . ./server.functions else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log + 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 "$(date) fatal: server.properties is missing" >> "fatalerror.log" echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" exit 1 fi @@ -29,16 +29,16 @@ fi if [[ -s "server.settings" ]]; then . ./server.settings else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log + 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} + cd "${serverdirectory}" else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log + echo "$(date) fatal: serverdirectory is missing" >> "fatalerror.log" echo "${red}fatal: serverdirectory is missing${nocolor}" exit 1 fi @@ -50,66 +50,33 @@ CheckDebug "executing vent script" ParseScriptArguments "$@" # 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" +PrintToTerminal "warn" "are you sure you want to vent your server?" +read -p "if so, please type ${red}confirm venting${nocolor} " +if [[ ${REPLY} == "confirm venting" ]]; then + PrintToTerminal "info" "user confirmed venting - server will self-destruct now" else - echo "wrong token - please try again" + PrintToTerminal "error" "wrong token - please 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 +PrintToLog "action" "${date} executing self-destruct script" "${screenlog}" # 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')" +PrintToTerminal "action" "self-destructing server" +PrintToScreen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"self-destructing server\",\"color\":\"red\"}]" # sleep for 2 seconds sleep 2s -# check if immediately is specified -if ! [[ ${immediately} == true ]]; then +# check if now is specified +if ! [[ ${now} == 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')" + PrintToScreen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"server is self-destructing in ${counter} seconds\",\"color\":\"red\"}]" fi counter=$((counter-1)) sleep 1s @@ -118,41 +85,38 @@ fi # 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')" +PrintToScreen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"GAME OVER\",\"color\":\"red\"}]" # 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 - -# 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 +# check if server is running +if screen -list | grep -q "\.${servername}"; then + + # server stop + PerformServerStop + + # awaits server stop + AwaitServerStop + + # force quit server if not stopped + ConditionalForceQuit + + # output confirmed stop + PrintToLog "ok" "server successfully stopped!" "${screenlog}" + CheckQuiet "ok" "server successfully stopped!" + fi # sleep 2 seconds sleep 2s -cd ${homedirectory} +cd "${homedirectory}" # remove crontab crontab -r # remove serverdirectory echo "deleting server..." -rm -r ${servername} +rm -r "${servername}" # check if vent was successful if ! [ -d "${serverdirectory}" ]; then # game over terminal screen @@ -160,7 +124,7 @@ if ! [ -d "${serverdirectory}" ]; then exit 0 else # error if serverdirectory still exists - echo "${red}venting failed!${nocolor}" + PrintToTerminal "error" "venting failed!" exit 1 fi From 1a5d6f751f4c9ade4729689703c1670aece49967 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 9 Oct 2021 21:06:49 +0200 Subject: [PATCH 014/115] added address already in use check --- start.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/start.sh b/start.sh index 3eee3e3..0fd2d0d 100644 --- a/start.sh +++ b/start.sh @@ -159,6 +159,11 @@ while [ ${startupchecks} -lt 120 ]; do PrintToLog "error" "server port is already in use - please change to another port" "${screenlog}" exit 1 fi + if tail -20 "${screenlog}" | grep -q "Address already in use"; then + PrintToTerminal "error" "server address is already in use - please change to another port" + PrintToLog "error" "server address is already in use - please change to another port" "${screenlog}" + exit 1 + fi if ! screen -list | grep -q "${servername}"; then PrintToTerminal "fatal" "something went wrong - server appears to have crashed!" PrintToTerminal "info" "crash dump - last 10 lines of ${screenlog}" From 723eb7a0e55f30e1d57257b57b9328611b22adb4 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Wed, 27 Oct 2021 12:54:02 +0200 Subject: [PATCH 015/115] unified scripts into worker --- worker.sh | 101 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 73 insertions(+), 28 deletions(-) diff --git a/worker.sh b/worker.sh index c176fae..3753143 100644 --- a/worker.sh +++ b/worker.sh @@ -1,7 +1,7 @@ #!/bin/bash # minecraft server worker script -# can be executed detached with ./worker.sh & +# is meant to be executed detached with ./worker.sh & by start.sh # root safety check if [ $(id -u) = 0 ]; then @@ -13,14 +13,14 @@ fi if [[ -s "server.functions" ]]; then . ./server.functions else - echo "$(date) fatal: server.functions is missing" >> fatalerror.log + 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 "$(date) fatal: server.properties is missing" >> "fatalerror.log" echo "$(tput setaf 1)fatal: server.properties is missing$(tput sgr0)" exit 1 fi @@ -29,7 +29,7 @@ fi if [[ -s "server.settings" ]]; then . ./server.settings else - echo "$(date) fatal: server.settings is missing" >> fatalerror.log + echo "$(date) fatal: server.settings is missing" >> "fatalerror.log" echo "$(tput setaf 1)fatal: server.settings is missing$(tput sgr0)" exit 1 fi @@ -38,50 +38,95 @@ fi if [ -d "${serverdirectory}" ]; then cd ${serverdirectory} else - echo "$(date) fatal: serverdirectory is missing" >> fatalerror.log + 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 worker script" >> ${screenlog} +echo "${date} executing worker script" >> "${screenlog}" # check if server is running if ! screen -list | grep -q "\.${servername}"; then - echo "server is not currently running!" >> ${screenlog} + echo "server is not currently running!" >> "${screenlog}" echo "${yellow}server is not currently running!${nocolor}" exit 1 fi # check every second if a player with permission request a task +# write a function that checks if backups are done regularly +# if any irregularities are detected notify via ingame or logfiles +# 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" ) linebuffer=$(tail -1 "${screenlog}") -lastlinebuffer=${linebuffer} +lastabsolutebackupsize="65536" +lastabsoluteworldsize="65536" +lastlinebuffer="${linebuffer}" +counter="0" while true; do - linebuffer=$(tail -1 "${screenlog}") - if [[ ! ${linebuffer} == ${lastlinebuffer} ]]; then - # check if safety backup is enabled - if [[ ${enablesafetybackupstring} == true ]]; then - CheckSafetyBackupString + # welcome messages + if [[ ${welcomemessage} == true ]]; then + 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 - # check if safety backup is enabled - if [[ ${enableconfirmrestartstring} == true ]]; then - CheckConfirmRestartString - fi - # check if safety backup is enabled - if [[ ${enableconfirmupdatestring} == true ]]; then - CheckConfirmUpdateString + fi + # admin tasks + if [[ ${enabletasks} == true ]]; then + linebuffer=$(tail -1 "${screenlog}") + if [[ ! ${linebuffer} == ${lastlinebuffer} ]]; then + if [[ ${enablesafetybackupstring} == true ]]; then # check if safety backup is enabled + CheckSafetyBackupString + fi + if [[ ${enableconfirmrestartstring} == true ]]; then # check if safety backup is enabled + CheckConfirmRestartString + fi + if [[ ${enableconfirmupdatestring} == true ]]; then # check if safety backup is enabled + CheckConfirmUpdateString + fi + if [[ ${enableconfirmresetstring} == true ]]; then # check if safety backup is enabled + CheckConfirmResetString + fi fi - # check if safety backup is enabled - if [[ ${enableconfirmresetstring} == true ]]; then - CheckConfirmResetString + linebuffer=$(tail -1 "${screenlog}") # store last line of screen log into buffer + fi + # watchdog + if [[ ${enablewatchdog} == true ]]; then + 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 fi - # store last line of screen log into buffer - linebuffer=$(tail -1 "${screenlog}") - # exit check if server is shut down + # autostart on crash or exit if ! screen -list | grep -q "\.${servername}"; then - exit 0 + if [[ ${enablestartoncrash} == true ]]; then + ./start.sh --quiet + else + exit 0 + fi fi - lastlinebuffer=${linebuffer} + # variables + lastlinebuffer="${linebuffer}" + counter=$((counter+1)) sleep 1s done From c01c6e671d043c9df689ef54f67d8aef8f5f3eae Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Wed, 27 Oct 2021 12:54:14 +0200 Subject: [PATCH 016/115] fixed typo --- server.functions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.functions b/server.functions index 42448b8..2a2e428 100644 --- a/server.functions +++ b/server.functions @@ -60,7 +60,7 @@ function CheckQuiet { fi } -# prints all unpit to terminal +# prints all input to terminal function PrintToTerminal { if [[ $1 == "ok" ]]; then echo "${green}ok: ${2}${nocolor}" From b97066e023f4746eb9f7fb3092530958bce5eaa8 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Wed, 27 Oct 2021 12:54:27 +0200 Subject: [PATCH 017/115] added autostart on crash option --- server.settings | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/server.settings b/server.settings index 9161aa4..98c4817 100644 --- a/server.settings +++ b/server.settings @@ -77,13 +77,19 @@ 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 +# enables an autostart triggered by a server crash +enablestartoncrash="replaceenablestartoncrash" # let your server autostart in case of a crash + # network stuff dnsserver="replacednsserver" # server will ping it for public avalability checks interface="replaceinterface" # server will ping it for private avalability checks From 7e45068567bc0b4219ed222cba86ccb256224705 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Wed, 27 Oct 2021 12:54:52 +0200 Subject: [PATCH 018/115] no longer necessary --- watchdog.sh | 87 ----------------------------------------------------- welcome.sh | 73 -------------------------------------------- 2 files changed, 160 deletions(-) delete mode 100644 watchdog.sh delete mode 100644 welcome.sh 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 From cf5ae425957341386a5935e700bd780b5917b202 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Wed, 27 Oct 2021 12:55:19 +0200 Subject: [PATCH 019/115] worker adjustments --- start.sh | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/start.sh b/start.sh index 0fd2d0d..478db1b 100644 --- a/start.sh +++ b/start.sh @@ -205,28 +205,33 @@ if ! tail "${screenlog}" | grep -q "Thread Query Listener started"; then PrintToLog "warn" "server startup unsuccessful - perhaps query is disabled" "${screenlog}" fi +# execute server worker +./worker.sh & + # enables the watchdog script for backup integrity if [[ "${enablewatchdog}" == true ]]; then CheckVerbose "info" "activating watchdog..." - ./watchdog.sh & fi # check if user wants to send welcome messages if [[ "${welcomemessage}" == true ]]; then CheckVerbose "info" "activating welcome messages..." - ./welcome.sh & fi # check if user wants to enable task execution if [[ "${enabletasks}" == true ]]; then CheckVerbose "info" "activating task execution..." - ./worker.sh & +fi + +# check if user wants to enable task execution +if [[ "${enablestartoncrash}" == true ]]; then + CheckVerbose "info" "activating auto start on crash..." fi # if set to true change automatically to server console if [[ "${changetoconsole}" == true ]]; then CheckVerbose "info" "changing to server console..." - screen -r ${servername} + screen -r "${servername}" fi # user information From d9a26790bfa832214d4f9406e1efe65caeb57a40 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Wed, 27 Oct 2021 12:55:33 +0200 Subject: [PATCH 020/115] cleaning up setup script --- setup.sh | 161 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 85 insertions(+), 76 deletions(-) diff --git a/setup.sh b/setup.sh index b93a857..c10a602 100644 --- a/setup.sh +++ b/setup.sh @@ -21,29 +21,44 @@ cyan="$(tput setaf 6)" white="$(tput setaf 7)" nocolor="$(tput sgr0)" +# prints all input to terminal +function PrintToTerminal { + if [[ $1 == "ok" ]]; then + echo "${green}ok: ${2}${nocolor}" + fi + if [[ $1 == "info" ]]; then + echo "${nocolor}info: ${2}${nocolor}" + fi + if [[ $1 == "warn" ]]; then + echo "${yellow}warn: ${2}${nocolor}" + fi + if [[ $1 == "error" ]]; then + echo "${red}error: ${2}${nocolor}" + fi + if [[ $1 == "fatal" ]]; then + echo "${red}fatal: ${2}${nocolor}" + fi + if [[ $1 == "action" ]]; then + echo "${cyan}action: ${2}${nocolor}" + fi +} + # parse script arguments -immediately=false -quiet=false -verbose=false +auto=false +nerdy=false while [[ $# -gt 0 ]]; do case "$1" in - -i) - immediately=true - ;; - -q) - quiet=true + -a) + auto=true ;; - -v) - verbose=true + -n) + nerdy=true ;; - --immediately) - immediately=true + --auto) + auto=true ;; - --quiet) - quiet=true - ;; - --verbose) - verbose=true + --nerdy) + nerdy=true ;; *) echo "bad argument: $1" @@ -106,7 +121,7 @@ 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" + echo "${red}fatal: the package ${packages[${i}-1]} is not installed on your system${nocolor}" exit 1 fi done @@ -121,12 +136,12 @@ read -re -i "minecraft" -p "Your name: " servername regex="^[a-zA-Z0-9]+$" verify="false" while [[ ${verify} == "false" ]]; do - if [[ ! ${servername} =~ ${regex} ]]; then + if [[ ! "${servername}" =~ ${regex} ]]; then read -p "Please enter a servername which only contains letters and numbers: " servername else check1="true" fi - if [ -d ${servername} ]; then + if [ -d "${servername}" ]; then read -p "Directory ${servername} already exists - please enter another directory: " servername else check2="true" @@ -161,38 +176,23 @@ 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} +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} + 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}" + 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} + wget -q -O "${1}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${1}" fi } # user info about download -echo "info: downloading scripts from GitHub... " +echo "info: downloading scripts from github... " # downloading scripts from github # declare all scripts in an array @@ -221,9 +221,9 @@ serverdirectory=`pwd` echo "${green}ok: download successful${nocolor}" # function for downloading serverfile from mojang api with error checking -function FetchServerFileFromMojan { +function FetchServerFileFromMojang { echo -n "downloading minecraft-server.${version}.jar... " - wget -q -O minecraft-server.${version}.jar https://launcher.mojang.com/v1/objects/${1}/server.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 @@ -232,32 +232,32 @@ function FetchServerFileFromMojan { } # download java executable from mojang.com -PS3="Which server version would you like to install? " +PS3="which server version would you like to install? " versions=("1.17.1" "1.16.5" "1.16.4" "1.16.3") select version in "${versions[@]}"; do case ${version} in "1.17.1") - FetchServerFileFromMojan "a16d67e5807f57fc4e550299cf20226194497dc2" + FetchServerFileFromMojang "a16d67e5807f57fc4e550299cf20226194497dc2" break ;; "1.16.5") - FetchServerFileFromMojan "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" + FetchServerFileFromMojang "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" break ;; "1.16.4") - FetchServerFileFromMojan "35139deedbd5182953cf1caa23835da59ca3d7cd" + FetchServerFileFromMojang "35139deedbd5182953cf1caa23835da59ca3d7cd" break ;; "1.16.3") - FetchServerFileFromMojan "f02f4473dbf152c23d7d484952121db0b36698cb" + FetchServerFileFromMojang "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" +echo "your Server will execute ${green}${serverfile}${nocolor} at start" # set up backupdirectory with child directories echo -n "info: setting up a backupdirectory... " @@ -278,28 +278,37 @@ mkdir backups 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 -done +if [[ ${nerdy} == true ]] || [[ ${nerdy} == true ]]; then + if [[ ${nerdy} == true ]]; then + nerdysetup=true + fi + if [[ ${auto} == true ]]; then + nerdysetup=false + fi +else + # ask user for setup method + 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 + done +fi # check if nerdysetup is true if [[ ${nerdysetup} == true ]]; then @@ -716,8 +725,8 @@ 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 "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} @@ -932,9 +941,9 @@ while [[ ! ${REPLY} =~ ${regex} ]]; do read -p "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 From 67642c5b5bb145a8a08de0ccd7f040302de521f8 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 27 Nov 2021 14:33:29 +0100 Subject: [PATCH 021/115] use dev instead of main branch --- server.settings | 2 +- setup.sh | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/server.settings b/server.settings index 98c4817..8652e83 100644 --- a/server.settings +++ b/server.settings @@ -67,7 +67,7 @@ enableconfirmupdatestring="false" # enables confirm update string to perform an 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 +branch="replacebranch" # all scripts will fetch from this branch # enables debug logging enabledebug="false" # enables debug log into logfiles if set to true diff --git a/setup.sh b/setup.sh index c10a602..c16270a 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)" @@ -196,7 +196,7 @@ echo "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" ) +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" "worker.sh" "vent.sh" ) # get length of script array scriptslength=${#scripts1[@]} # loop through all entries in the array @@ -695,6 +695,7 @@ echo -n "storing variables in server.settings... " StoreToSettings "replaceserverdirectory" "${serverdirectory}" StoreToSettings "replacebackupdirectory" "${backupdirectory}" StoreToSettings "replaceserverfile" "${serverfile}" + StoreToSettings "replacebranch" "${branch}" echo "done" # store all the userinput From d9b3d863c0c3980a525f90fe47f5975b63508acf Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 6 Dec 2021 13:09:57 +0100 Subject: [PATCH 022/115] prepping for minecraft 1.18 --- setup.sh | 28 ++++++++++++---------------- update.sh | 8 ++++---- 2 files changed, 16 insertions(+), 20 deletions(-) diff --git a/setup.sh b/setup.sh index c16270a..3ffa381 100644 --- a/setup.sh +++ b/setup.sh @@ -127,12 +127,12 @@ for (( i = 1; i < ${packageslength} + 1; i ++ )); do done # user info about script -echo "${cyan}I will setup a minecraft server for you${nocolor} ${blue};^)${nocolor}" +echo "${cyan}i will setup a minecraft server for you${nocolor} ${blue};^)${nocolor}" # 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 +echo "how should I call your server?" +echo "please enter a servername: example: ${yellow}minecraft${nocolor}" +read -re -i "minecraft" -p "your name: " servername regex="^[a-zA-Z0-9]+$" verify="false" while [[ ${verify} == "false" ]]; do @@ -152,7 +152,7 @@ while [[ ${verify} == "false" ]]; do verify="false" fi done -echo "Your Server will be called ${green}${servername}${nocolor}" +echo "your server will be called ${green}${servername}${nocolor}" # store homedirectory homedirectory=`pwd` @@ -172,7 +172,7 @@ if [[ $REPLY =~ ^[Yy]$ ]] fi # set up directorys -echo "I will now setup a server and backup directory." +echo "i will now setup a server and backup directory." # set up server directory echo -n "info: setting up a serverdirectory... " @@ -233,24 +233,20 @@ function FetchServerFileFromMojang { # 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") +versions=("1.18.0" "1.17.1" "1.16.5" "1.16.4" "1.16.3") select version in "${versions[@]}"; do case ${version} in + "1.18.0") + FetchServerFileFromMojang "3cf24a8694aca6267883b17d934efacc5e44440d" + break + ;; "1.17.1") FetchServerFileFromMojang "a16d67e5807f57fc4e550299cf20226194497dc2" break - ;; + ;; "1.16.5") FetchServerFileFromMojang "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" break - ;; - "1.16.4") - FetchServerFileFromMojang "35139deedbd5182953cf1caa23835da59ca3d7cd" - break - ;; - "1.16.3") - FetchServerFileFromMojang "f02f4473dbf152c23d7d484952121db0b36698cb" - break ;; *) echo "please choose an option from the list: ";; esac diff --git a/update.sh b/update.sh index 18a0e8a..2facf61 100644 --- a/update.sh +++ b/update.sh @@ -74,7 +74,7 @@ fi CreateCachedBackup "update" # Test internet connectivity and update on success -wget --spider --quiet "https://launcher.mojang.com/v1/objects/a16d67e5807f57fc4e550299cf20226194497dc2/server.jar" +wget --spider --quiet "https://launcher.mojang.com/v1/objects/3cf24a8694aca6267883b17d934efacc5e44440d/server.jar" if [ "$?" != 0 ]; then PrintToTerminal "warn" "unable to connect to mojang api skipping update..." PrintToLog "warn" "unable to connect to mojang api skipping update..." "${screenlog}" @@ -86,12 +86,12 @@ else CheckVerbose "info" "you are running the newest server version - skipping update" PrintToLog "info" "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" + wget -q -O "minecraft-server.1.18.0.jar" "https://launcher.mojang.com/v1/objects/3cf24a8694aca6267883b17d934efacc5e44440d/server.jar" # update serverfile variable in server.settings - newserverfile="${serverdirectory}/minecraft-server.1.17.1.jar" + newserverfile="${serverdirectory}/minecraft-server.1.18.0.jar" # if new serverfile exists remove oldserverfile if [ -f "${newserverfile}" ]; then - CheckVerbose "ok" "updating server.settings for startup with new server version 1.17.1" + CheckVerbose "ok" "updating server.settings for startup with new server version 1.18.0" sed -i "s|${serverfile}|${newserverfile}|g" "server.settings" # remove old serverfile if it exists if [ -f "${serverfile}" ]; then From 12abda7784a76f90939f1032f29defcdc1e0ef69 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 6 Dec 2021 15:16:43 +0100 Subject: [PATCH 023/115] restructure and new version --- setup.sh | 964 ++++++++++++++----------------------------------------- 1 file changed, 233 insertions(+), 731 deletions(-) diff --git a/setup.sh b/setup.sh index 3ffa381..3fb9254 100644 --- a/setup.sh +++ b/setup.sh @@ -43,75 +43,82 @@ function PrintToTerminal { fi } -# parse script arguments -auto=false -nerdy=false -while [[ $# -gt 0 ]]; do - case "$1" in - -a) - auto=true - ;; - -n) - nerdy=true - ;; - --auto) - auto=true - ;; - --nerdy) - nerdy=true - ;; - *) - echo "bad argument: $1" - exit 1 - ;; - esac - shift -done - # 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)" + PrintToTerminal "fatal" "please do not run me as root :( - this is dangerous!" exit 1 fi -# 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)" - 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)" - 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 Linux +function CheckForLinux { + if [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then + # inform user about Linux + PrintToTerminal "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 + PrintToTerminal "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 + PrintToTerminal "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 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 macOS +function CheckForMacOS { + if [ "$(uname)" == "Darwin" ]; then + # inform user about macOS + PrintToTerminal "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 + PrintToTerminal "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 + PrintToTerminal "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 10)" == "MINGW64_NT" ]; then +} + +# check for Windows +function CheckForWindows { + if [ "$(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)" + PrintToTerminal "fatal" "you are running Windows as your operating system - your server will not run!" + supported=false 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 + fi +} + +# check for unsupported OS +function CheckForUnsupportedOS { + if [ supported == false ]; then + # inform user about unsupported operating system + PrintToTerminal "fatal" "you are running an unsupported operating system - your server will not run!" + exit 1 + fi +} + +# run all checks +CheckForLinux +CheckForMacOS +CheckForWindows +CheckForUnsupportedOS # check if every required package is installed # declare all packages in an array @@ -119,51 +126,48 @@ declare -a packages=( "apt" "java" "screen" "date" "tar" "echo" "ping" "grep" "w # get length of package array packageslength=${#packages[@]} # use for loop to read all values and indexes -for (( i = 1; i < ${packageslength} + 1; i ++ )); do +for (( i = 0; i < ${packageslength}; 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${nocolor}" + PrintToTerminal "fatal" "the package ${packages[${i}]} is not installed on your system" exit 1 fi done # user info about script -echo "${cyan}i will setup a minecraft server for you${nocolor} ${blue};^)${nocolor}" +PrintToTerminal "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 "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 + read -p "please enter a servername 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 + read -p "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" fi done -echo "your server will be called ${green}${servername}${nocolor}" +PrintToTerminal "info" "your server will be called ${green}${servername}${nocolor}" # store homedirectory 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]: " +PrintToTerminal "info" "i will download start, stop, restart, backup and many more scripts from github" +read -p "proceed? (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY + read -p "please press y or n: " REPLY done if [[ $REPLY =~ ^[Yy]$ ]] then echo "${green}starting setup...${nocolor}" @@ -171,20 +175,16 @@ if [[ $REPLY =~ ^[Yy]$ ]] 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... " +PrintToTerminal "info" "setting up a serverdirectory..." mkdir "${servername}" cd "${servername}" -echo "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}" + PrintToTerminal "fatal" "unable to connect to github api. script will exit! (maybe chose another branch?)" exit 1 else wget -q -O "${1}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${1}" @@ -192,48 +192,48 @@ function FetchScriptFromGitHub { } # user info about download -echo "info: downloading scripts from github... " +PrintToTerminal "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" "worker.sh" "vent.sh" ) +declare -a scriptsdownload=( "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" "worker.sh" "vent.sh" ) # get length of script array -scriptslength=${#scripts1[@]} +scriptslength=${#scriptsdownload[@]} # loop through all entries in the array -for (( i = 1; i < ${scriptslength} + 1; i ++ )); do - FetchScriptFromGitHub "${scripts1[${i}-1]}" +for (( i = 0; i < ${scriptslength}; i ++ )); do + FetchScriptFromGitHub "${scriptsdownload[${i}]}" done +# user info about download +PrintToTerminal "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" ) +declare -a scriptsexecutable=( "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[@]} +scriptslength=${#scriptsexecutable[@]} # 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]} +for (( i = 0; i < ${scriptslength}; 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 FetchServerFileFromMojang { - echo -n "downloading minecraft-server.${version}.jar... " + PrintToTerminal "info" "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}" + PrintToTerminal "ok" "download successful" if ! [[ -s "minecraft-server.${version}.jar" ]]; then - echo "download error: downloaded server-file minecraft-server.${version}.jar is empty or not available" + PrintToTerminal "fatal" "downloaded server-file minecraft-server.${version}.jar is empty or not available" fi } # download java executable from mojang.com PS3="which server version would you like to install? " -versions=("1.18.0" "1.17.1" "1.16.5" "1.16.4" "1.16.3") +versions=("1.18.0" "1.17.1" "1.16.5") select version in "${versions[@]}"; do case ${version} in "1.18.0") @@ -253,415 +253,72 @@ select version in "${versions[@]}"; do done # user information about execute at start -echo "your Server will execute ${green}${serverfile}${nocolor} at start" +PrintToTerminal "info" "your server will execute ${serverfile} at start" # set up backupdirectory with child directories -echo -n "info: setting up a backupdirectory... " +PrintToTerminal "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" - -if [[ ${nerdy} == true ]] || [[ ${nerdy} == true ]]; then - if [[ ${nerdy} == true ]]; then - nerdysetup=true - fi - if [[ ${auto} == true ]]; then - nerdysetup=false - fi -else - # ask user for setup method - 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 - done -fi - -# 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 ;^)" +cd backups + +# declare all backup children in an array +declare -a backupchildren=( "hourly" "daily" "weekly" "monthly" "cached") +# get length of backup children array +scriptslength=${#backupchildren[@]} +for (( i = 0; i < ${scriptslength}; i ++ )); do + PrintToTerminal "info" "creating ${serverdirectory}/backups/${scriptslength[${i}-1]}" + mkdir "${scriptslength[${i}]}" +done -fi +backupdirectory=`pwd` +cd ${serverdirectory} + +# 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 ;^)" # 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]: " +PrintToTerminal "info" "would you like to accept the end user license agreement from mojang?" +PrintToTerminal "info" "if you say no your server will not be able to run" +PrintToTerminal "info" "if you say yes you must abide by their terms and conditions!" +read -p "(y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "Please press Y or N: " REPLY + read -p "please press y or n: " REPLY done if [[ ${REPLY} =~ ^[Yy]$ ]] - then echo "${green}accepting eula...${nocolor}" + then PrintToTerminal "ok" "accepting eula..." echo "eula=true" >> eula.txt - else echo "${red}declining eula...${nocolor}" + else PrintToTerminal "error" "declining eula..." echo "eula=false" >> eula.txt fi @@ -676,266 +333,111 @@ function StoreToProperties { } # 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}" - StoreToSettings "replacebranch" "${branch}" -echo "done" +PrintToTerminal "info" "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}" +StoreToSettings "replacebranch" "${branch}" # 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" +PrintToTerminal "info" "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}" # 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} +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 +# user info +PrintToTerminal "info" "storing config to crontab..." - # 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 +# 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 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 e-mail config +StoreToCrontab "#MAILTO=youremail@example.com" - # 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 +# define colors for tput +StoreToCrontab "TERM=xterm" +StoreToCrontab "" - # 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 backups +StoreToCrontab "# minecraft ${servername} server backup hourly at **:00" +StoreToCrontab "0 * * * * cd ${serverdirectory} && ./backup.sh --quiet" - # 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 +# 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" - # padd crontab with two empty lines - StoreToCrontab "" - StoreToCrontab "" +# crontab automatization restart +StoreToCrontab "# minecraft ${servername} server restart at 02:00 on Sundays" +StoreToCrontab "#0 12 * * 0 cd ${serverdirectory} && ./restart.sh --quiet" - # 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 automatization updates +StoreToCrontab "# minecraft ${servername} server update at 18:00 on Sundays" +StoreToCrontab "#0 18 * * 0 cd ${serverdirectory} && ./update.sh --quiet" - # crontab e-mail config - StoreToCrontab "#MAILTO=youremail@example.com" +# crontab automatization startup +StoreToCrontab "# minecraft ${servername} server startup at boot" +StoreToCrontab "@reboot cd ${serverdirectory} && ./start.sh --quiet" - # define colors for tput - StoreToCrontab "TERM=xterm" - StoreToCrontab "" +# padd crontab with two empty lines +StoreToCrontab "" +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 "" - -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}" +PrintToTerminal "ok" "setup is complete!" +PrintToTerminal "info" "if you would like to start your server" +PrintToTerminal "info" "go into your ${green}${serverdirectory}${nocolor} directory" +PrintToTerminal "info" "and execute ${green}./start.sh${nocolor}" +PrintToTerminal "info" "god luck and have fun! ;^)" # ask user for removal of setup script -read -p "Would you like to remove the setup script? [Y/N]: " +read -p "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 "please press y or n: " REPLY done if [[ ${REPLY} =~ ^[Yy]$ ]]; then cd "${homedirectory}" @@ -944,16 +446,16 @@ if [[ ${REPLY} =~ ^[Yy]$ ]]; then fi # ask user to start server now -read -p "Would you like to start your server now? [Y/N]: " +read -p "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 "please press y or n: " REPLY done if [[ ${REPLY} =~ ^[Yy]$ ]]; then - echo "${cyan}action: starting up server...${nocolor}" + PrintToTerminal "action" "starting up server..." ./start.sh --verbose else - echo "${green}ok: script has finished!${nocolor}" + PrintToTerminal "ok" "script has finished!" fi # exit with code 0 From edbc92c784db9b952112ec15e6dd75d1699e7ac3 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 6 Dec 2021 15:21:14 +0100 Subject: [PATCH 024/115] bugfixes --- setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.sh b/setup.sh index 3fb9254..dbd6a71 100644 --- a/setup.sh +++ b/setup.sh @@ -267,7 +267,7 @@ declare -a backupchildren=( "hourly" "daily" "weekly" "monthly" "cached") scriptslength=${#backupchildren[@]} for (( i = 0; i < ${scriptslength}; i ++ )); do PrintToTerminal "info" "creating ${serverdirectory}/backups/${scriptslength[${i}-1]}" - mkdir "${scriptslength[${i}]}" + mkdir "${backupchildren[${i}]}" done backupdirectory=`pwd` From 231e955dffe0543d949c6d600b8fa6d4536fad06 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 6 Dec 2021 15:27:28 +0100 Subject: [PATCH 025/115] remove unnecessary log --- setup.sh | 6 ------ 1 file changed, 6 deletions(-) diff --git a/setup.sh b/setup.sh index dbd6a71..2716610 100644 --- a/setup.sh +++ b/setup.sh @@ -374,12 +374,6 @@ StoreToProperties "query.port=25565" "${queryport}" StoreToProperties "enable-query=false" "${enablequery}" StoreToProperties "motd=A Minecraft Server" "${motd}" -# create logfiles with welcome message -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 - From e4d310b2840cf81054303f9175e34cf3e548846b Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 6 Dec 2021 15:30:38 +0100 Subject: [PATCH 026/115] more fixes and styling --- setup.sh | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/setup.sh b/setup.sh index 2716610..abb8b39 100644 --- a/setup.sh +++ b/setup.sh @@ -209,7 +209,7 @@ PrintToTerminal "ok" "download successful" # make selected scripts executable # declare all scripts in an array -declare -a scriptsexecutable=( "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" ) +declare -a scriptsexecutable=( "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "maintenance.sh" "prerender.sh" "worker.sh" "vent.sh" ) # get length of script array scriptslength=${#scriptsexecutable[@]} # loop through all entries in the array @@ -260,7 +260,6 @@ PrintToTerminal "info" "setting up a backupdirectory..." mkdir world mkdir backups cd backups - # declare all backup children in an array declare -a backupchildren=( "hourly" "daily" "weekly" "monthly" "cached") # get length of backup children array @@ -269,7 +268,6 @@ for (( i = 0; i < ${scriptslength}; i ++ )); do PrintToTerminal "info" "creating ${serverdirectory}/backups/${scriptslength[${i}-1]}" mkdir "${backupchildren[${i}]}" done - backupdirectory=`pwd` cd ${serverdirectory} @@ -419,7 +417,6 @@ StoreToCrontab "@reboot cd ${serverdirectory} && ./start.sh --quiet" StoreToCrontab "" StoreToCrontab "" - # finish messages PrintToTerminal "ok" "setup is complete!" PrintToTerminal "info" "if you would like to start your server" From c4fa9fe33ba1a29163e60481578703aa8f25b89d Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 6 Dec 2021 15:42:40 +0100 Subject: [PATCH 027/115] variable naming --- setup.sh | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/setup.sh b/setup.sh index abb8b39..4c1472e 100644 --- a/setup.sh +++ b/setup.sh @@ -198,9 +198,9 @@ PrintToTerminal "info" "downloading scripts from github..." # declare all scripts in an array declare -a scriptsdownload=( "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" "worker.sh" "vent.sh" ) # get length of script array -scriptslength=${#scriptsdownload[@]} +arraylength=${#scriptsdownload[@]} # loop through all entries in the array -for (( i = 0; i < ${scriptslength}; i ++ )); do +for (( i = 0; i < ${arraylength}; i ++ )); do FetchScriptFromGitHub "${scriptsdownload[${i}]}" done @@ -211,9 +211,9 @@ PrintToTerminal "ok" "download successful" # declare all scripts in an array declare -a scriptsexecutable=( "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "maintenance.sh" "prerender.sh" "worker.sh" "vent.sh" ) # get length of script array -scriptslength=${#scriptsexecutable[@]} +arraylength=${#scriptsexecutable[@]} # loop through all entries in the array -for (( i = 0; i < ${scriptslength}; i ++ )); do +for (( i = 0; i < ${arraylength}; i ++ )); do chmod +x "${scriptsexecutable[${i}]}" done @@ -261,11 +261,10 @@ mkdir world mkdir backups cd backups # declare all backup children in an array -declare -a backupchildren=( "hourly" "daily" "weekly" "monthly" "cached") +declare -a backupchildren=( "hourly" "daily" "weekly" "monthly" "cached" ) # get length of backup children array -scriptslength=${#backupchildren[@]} -for (( i = 0; i < ${scriptslength}; i ++ )); do - PrintToTerminal "info" "creating ${serverdirectory}/backups/${scriptslength[${i}-1]}" +arraylength=${#backupchildren[@]} +for (( i = 0; i < ${arraylength}; i ++ )); do mkdir "${backupchildren[${i}]}" done backupdirectory=`pwd` From a1125c2c5e356058dd053c10656492bb0b04b8da Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 6 Dec 2021 15:47:32 +0100 Subject: [PATCH 028/115] removed watchdog and welcome scripts from helper --- server.functions | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/server.functions b/server.functions index 2a2e428..3cd0819 100644 --- a/server.functions +++ b/server.functions @@ -249,7 +249,7 @@ function RemoveScriptsFromServerDirectory { 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" ) + declare -a scripts=( "LICENSE" "README.md" "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "maintenance.sh" "prerender.sh" "worker.sh" "vent.sh" ) # get length of script array scriptslength=${#scripts[@]} # loop through all entries in the array @@ -265,7 +265,7 @@ function DownloadScriptsFromGitHub { 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" ) + declare -a scripts=( "LICENSE" "README.md" "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "maintenance.sh" "prerender.sh" "worker.sh" "vent.sh" ) # get length of script array scriptslength=${#scripts[@]} # loop through all entries in the array @@ -278,7 +278,7 @@ function DownloadScriptsFromGitHub { function MakeScriptsExecutable { # 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" ) + declare -a scripts=( "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "maintenance.sh" "prerender.sh" "worker.sh" "vent.sh" ) # get length of script array scriptslength=${#scripts[@]} # loop through all entries in the array From 1b739ba4ab76412ce176c66f0ba287e410a65b24 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 6 Dec 2021 15:50:37 +0100 Subject: [PATCH 029/115] more functions instead of hardcode --- setup.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.sh b/setup.sh index 4c1472e..55b42b1 100644 --- a/setup.sh +++ b/setup.sh @@ -170,8 +170,8 @@ while [[ ! ${REPLY} =~ ${regex} ]]; do read -p "please press y or n: " REPLY done if [[ $REPLY =~ ^[Yy]$ ]] - then echo "${green}starting setup...${nocolor}" - else echo "${red}exiting...${nocolor}" + then PrintToTerminal "ok" "starting setup..." + else PrintToTerminal "error" "exiting..." exit 1 fi From 098c9b5697ee328d593659eeb89411e274de0736 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 6 Dec 2021 15:54:07 +0100 Subject: [PATCH 030/115] added quiet option to initial download --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ea8bbef..9f4ecee 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ sudo apt install openjdk-17-jre-headless iputils-ping net-tools mailutils coreut Then, you can download and execute the setup script.
This command downloads, makes executable and executes the setup script. ``` -wget -O setup.sh https://raw.githubusercontent.com/Simylein/MinecraftServer/main/setup.sh && chmod +x setup.sh && ./setup.sh +wget -q -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 pre-filled 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 From 4a76d6b0ca6fc9632244e9eb713048af6c21da79 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Fri, 10 Dec 2021 16:40:05 +0100 Subject: [PATCH 031/115] updated to server version 1.18.1 --- setup.sh | 6 +++--- update.sh | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/setup.sh b/setup.sh index 55b42b1..761e21d 100644 --- a/setup.sh +++ b/setup.sh @@ -233,11 +233,11 @@ function FetchServerFileFromMojang { # download java executable from mojang.com PS3="which server version would you like to install? " -versions=("1.18.0" "1.17.1" "1.16.5") +versions=("1.18.1" "1.17.1" "1.16.5") select version in "${versions[@]}"; do case ${version} in - "1.18.0") - FetchServerFileFromMojang "3cf24a8694aca6267883b17d934efacc5e44440d" + "1.18.1") + FetchServerFileFromMojang "125e5adf40c659fd3bce3e66e67a16bb49ecc1b9" break ;; "1.17.1") diff --git a/update.sh b/update.sh index 2facf61..66a8d44 100644 --- a/update.sh +++ b/update.sh @@ -74,7 +74,7 @@ fi CreateCachedBackup "update" # Test internet connectivity and update on success -wget --spider --quiet "https://launcher.mojang.com/v1/objects/3cf24a8694aca6267883b17d934efacc5e44440d/server.jar" +wget --spider --quiet "https://launcher.mojang.com/v1/objects/125e5adf40c659fd3bce3e66e67a16bb49ecc1b9/server.jar" if [ "$?" != 0 ]; then PrintToTerminal "warn" "unable to connect to mojang api skipping update..." PrintToLog "warn" "unable to connect to mojang api skipping update..." "${screenlog}" @@ -82,16 +82,16 @@ else CheckQuiet "ok" "downloading newest server version..." PrintToLog "info" "downloading newest server version..." "${screenlog}" # check if already on newest version - if [[ "${serverfile}" = *"minecraft-server.1.17.1.jar" ]]; then + if [[ "${serverfile}" = *"minecraft-server.1.18.1.jar" ]]; then CheckVerbose "info" "you are running the newest server version - skipping update" PrintToLog "info" "you are running the newest server version - skipping update" "${screenlog}" else - wget -q -O "minecraft-server.1.18.0.jar" "https://launcher.mojang.com/v1/objects/3cf24a8694aca6267883b17d934efacc5e44440d/server.jar" + wget -q -O "minecraft-server.1.18.1.jar" "https://launcher.mojang.com/v1/objects/125e5adf40c659fd3bce3e66e67a16bb49ecc1b9/server.jar" # update serverfile variable in server.settings newserverfile="${serverdirectory}/minecraft-server.1.18.0.jar" # if new serverfile exists remove oldserverfile if [ -f "${newserverfile}" ]; then - CheckVerbose "ok" "updating server.settings for startup with new server version 1.18.0" + CheckVerbose "ok" "updating server.settings for startup with new server version 1.18.1" sed -i "s|${serverfile}|${newserverfile}|g" "server.settings" # remove old serverfile if it exists if [ -f "${serverfile}" ]; then From 4f1c9a28abadc5a74611d4eea89053d128d4f81e Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Fri, 10 Dec 2021 16:43:06 +0100 Subject: [PATCH 032/115] fixed irregular whitespace --- start.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/start.sh b/start.sh index 478db1b..a0afdf8 100644 --- a/start.sh +++ b/start.sh @@ -159,7 +159,7 @@ while [ ${startupchecks} -lt 120 ]; do PrintToLog "error" "server port is already in use - please change to another port" "${screenlog}" exit 1 fi - if tail -20 "${screenlog}" | grep -q "Address already in use"; then + if tail -20 "${screenlog}" | grep -q "Address already in use"; then PrintToTerminal "error" "server address is already in use - please change to another port" PrintToLog "error" "server address is already in use - please change to another port" "${screenlog}" exit 1 From b9780ae375cf3278bed254fd0a0ff5ee09222235 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Fri, 10 Dec 2021 21:34:02 +0100 Subject: [PATCH 033/115] added script lock safety check --- maintenance.sh | 3 +++ prerender.sh | 3 +++ reset.sh | 3 +++ restart.sh | 3 +++ restore.sh | 3 +++ server.functions | 23 ++++++++++++++++++++++- server.settings | 3 +++ start.sh | 3 +++ stop.sh | 3 +++ update.sh | 3 +++ vent.sh | 3 +++ 11 files changed, 52 insertions(+), 1 deletion(-) diff --git a/maintenance.sh b/maintenance.sh index 8f8a8ba..3b55f8f 100644 --- a/maintenance.sh +++ b/maintenance.sh @@ -47,6 +47,9 @@ CheckDebug "executing maintenance script" # parsing script arguments ParseScriptArguments "$@" +# check for script lock +CheckScriptLock + # write date to logfile echo "action: ${date} executing maintenance script" >> ${screenlog} diff --git a/prerender.sh b/prerender.sh index 4b49491..41ffbc6 100644 --- a/prerender.sh +++ b/prerender.sh @@ -47,6 +47,9 @@ CheckDebug "executing pre-render script" # parsing script arguments ParseScriptArguments "$@" +# check for script lock +CheckScriptLock + # check if server is running if ! screen -list | grep -q "\.${servername}"; then PrintToTerminal "warn" "server is not currently running!" diff --git a/reset.sh b/reset.sh index 7efea9d..4a8c01a 100644 --- a/reset.sh +++ b/reset.sh @@ -47,6 +47,9 @@ CheckDebug "executing reset script" # parsing script arguments ParseScriptArguments "$@" +# check for script lock +CheckScriptLock + # write date to logfile PrintToLog "action" "${date} executing reset script" "${screenlog}" diff --git a/restart.sh b/restart.sh index 1d4d7ae..2274dc9 100644 --- a/restart.sh +++ b/restart.sh @@ -47,6 +47,9 @@ CheckDebug "executing restart script" # parsing script arguments ParseScriptArguments "$@" +# check for script lock +CheckScriptLock + # write date to logfile PrintToLog "action" "${date} executing restart script" "${screenlog}" diff --git a/restore.sh b/restore.sh index 5abf280..2c20538 100644 --- a/restore.sh +++ b/restore.sh @@ -47,6 +47,9 @@ CheckDebug "executing restore script" # parsing script arguments ParseScriptArguments "$@" +# check for script lock +CheckScriptLock + # write date to logfile echo "action: ${date} executing restore script" >> ${screenlog} diff --git a/server.functions b/server.functions index 3cd0819..21473d2 100644 --- a/server.functions +++ b/server.functions @@ -9,11 +9,15 @@ # function for parsing arguments for a script function ParseScriptArguments { + force=false now=false quiet=false verbose=false while [[ $# -gt 0 ]]; do case "$1" in + -f) + force=true + ;; -n) now=true ;; @@ -23,6 +27,9 @@ function ParseScriptArguments { -v) verbose=true ;; + --force) + force=true + ;; --now) now=true ;; @@ -33,7 +40,7 @@ function ParseScriptArguments { verbose=true ;; *) - echo "bad argument: $1" + echo "info: bad argument: $1" exit 1 ;; esac @@ -41,6 +48,20 @@ function ParseScriptArguments { done } +# checks if a script is already running +function CheckScriptLock { + if [[ ${force} == false ]] && [[ ${skipscriptlockcheck} == false ]]; then + declare -a arr=("maintenance.sh" "prerender.sh" "reset.sh" "restart.sh" "restore.sh" "start.sh" "stop.sh" "update.sh" "vent.sh") + for i in "${scriptslock[@]}"; do + if pidof -x "${scriptslock[i]}" &> /dev/null; then + echo "info: script ${scriptslock[i]} is already running" + echo "info: use --force option to ignore safety check" + exit 1 + fi + done + fi +} + # check if verbose mode is on function CheckVerbose { if [[ ${verbose} == true ]]; then diff --git a/server.settings b/server.settings index 8652e83..1bf4025 100644 --- a/server.settings +++ b/server.settings @@ -75,6 +75,9 @@ 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 +# script lock check +skipscriptlockcheck="false" # scripts will not check for other already running scripts if set to true + # change to server console after startup changetoconsole="replacechangetoconsole" # changes to server console after startup if set to true diff --git a/start.sh b/start.sh index a0afdf8..8f96046 100644 --- a/start.sh +++ b/start.sh @@ -55,6 +55,9 @@ CheckDebug "executing start script" # parsing script arguments ParseScriptArguments "$@" +# check for script lock +CheckScriptLock + # padd logfile for visibility echo "" >> "${screenlog}" echo "" >> "${screenlog}" diff --git a/stop.sh b/stop.sh index a58ff21..a45e6f1 100644 --- a/stop.sh +++ b/stop.sh @@ -47,6 +47,9 @@ CheckDebug "executing stop script" # parsing script arguments ParseScriptArguments "$@" +# check for script lock +CheckScriptLock + # write date to logfile PrintToLog "action" "${date} executing stop script" "${screenlog}" diff --git a/update.sh b/update.sh index 66a8d44..227e06f 100644 --- a/update.sh +++ b/update.sh @@ -47,6 +47,9 @@ CheckDebug "executing update script" # parsing script arguments ParseScriptArguments "$@" +# check for script lock +CheckScriptLock + # write date to logfile PrintToLog "action" "${date} executing update script" "${screenlog}" diff --git a/vent.sh b/vent.sh index 2a676e4..23bb388 100644 --- a/vent.sh +++ b/vent.sh @@ -49,6 +49,9 @@ CheckDebug "executing vent script" # parsing script arguments ParseScriptArguments "$@" +# check for script lock +CheckScriptLock + # user safety function for confirmation PrintToTerminal "warn" "are you sure you want to vent your server?" read -p "if so, please type ${red}confirm venting${nocolor} " From c885ea7f048fad3db3db3d5bc8c8d14733d3dfa1 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 21:41:11 +0100 Subject: [PATCH 034/115] feat: added nice values for backup processes --- backup.sh | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/backup.sh b/backup.sh index d441333..0a373c1 100644 --- a/backup.sh +++ b/backup.sh @@ -65,7 +65,7 @@ if [ ${dohourly} = true ]; then PrintToLog "action" "${date} executing backup-hourly script" "${screenlog}" PrintToLog "action" "${date} executing backup-hourly script" "${backuplog}" CheckDebug "executing backup-hourly script" - + # start milliseconds timer before=$(date +%s%3N) @@ -104,14 +104,14 @@ if [ ${dohourly} = true ]; then # disable auto save PrintToScreen "save-off" # run backup with compression - cp -r "world" "tmp" - tar -czf "world.tar.gz" "tmp" + nice -n 19 cp -r "world" "tmp" + nice -n 19 tar -czf "world.tar.gz" "tmp" # check for tar errors if [ "$?" != 0 ]; then CheckDebug "backup script reports tar error while performing backup-hourly" fi - mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/hourly/${servername}-${newhourly}.tar.gz" - rm -r "tmp" + nice -n 19 mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/hourly/${servername}-${newhourly}.tar.gz" + nice -n 19 rm -r "tmp" # enable auto save PrintToScreen "save-on" else @@ -206,14 +206,14 @@ if [ ${hours} -eq ${dailybackuptime} ]; then # disable auto save PrintToScreen "save-off" # run backup with compression - cp -r "world" "tmp" - tar -czf "world.tar.gz" "tmp" + nice -n 19 cp -r "world" "tmp" + nice -n 19 tar -czf "world.tar.gz" "tmp" # check for tar errors if [ "$?" != 0 ]; then CheckDebug "backup script reports tar error while performing backup-daily" fi - mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/daily/${servername}-${newdaily}.tar.gz" - rm -r "tmp" + nice -n 19 mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/daily/${servername}-${newdaily}.tar.gz" + nice -n 19 rm -r "tmp" # enable auto save PrintToScreen "save-on" else @@ -309,14 +309,14 @@ if [ ${hours} -eq ${dailybackuptime} ] && [ ${weekday} -eq ${weeklybackupday} ]; # disable auto save PrintToScreen "save-off" # run backup with compression - cp -r "world" "tmp" - tar -czf "world.tar.gz" "tmp" + nice -n 19 cp -r "world" "tmp" + nice -n 19 tar -czf "world.tar.gz" "tmp" # check for tar errors if [ "$?" != 0 ]; then CheckDebug "backup script reports tar error while performing backup-weekly" fi - mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/weekly/${servername}-${newweekly}.tar.gz" - rm -r "tmp" + nice -n 19 mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/weekly/${servername}-${newweekly}.tar.gz" + nice -n 19 rm -r "tmp" # enable auto save PrintToScreen "save-on" else @@ -412,14 +412,14 @@ if [ ${hours} -eq ${dailybackuptime} ] && [ ${dayofmonth} -eq ${monthlybackupday # disable auto save PrintToScreen "save-off" # run backup with compression - cp -r "world" "tmp" - tar -czf "world.tar.gz" "tmp" + nice -n 19 cp -r "world" "tmp" + nice -n 19 tar -czf "world.tar.gz" "tmp" # check for tar errors if [ "$?" != 0 ]; then CheckDebug "backup script reports tar error while performing backup-monthly" fi - mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/monthly/${servername}-${newmonthly}.tar.gz" - rm -r "tmp" + nice -n 19 mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/monthly/${servername}-${newmonthly}.tar.gz" + nice -n 19 rm -r "tmp" # enable auto save PrintToScreen "save-on" else From eea98ca13cc400eea6c95d1b41458c217c22ac2f Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 21:41:29 +0100 Subject: [PATCH 035/115] fix: fixed check debug function --- server.functions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.functions b/server.functions index 21473d2..e7a6743 100644 --- a/server.functions +++ b/server.functions @@ -71,7 +71,7 @@ function CheckVerbose { # checks if debug mode is on function CheckDebug { if [[ ${enabledebug} == true ]]; then - echo "$(date) ${1}" "debug.log" + echo "$(date) ${1}" >> "debug.log" fi } # check if quiet mode is on From 9afbe65307c2ced328feee67305d22bfcd2e4d46 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 21:41:52 +0100 Subject: [PATCH 036/115] feat: worker script features niceness and checks for enable --- start.sh | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/start.sh b/start.sh index 8f96046..a5bc3f0 100644 --- a/start.sh +++ b/start.sh @@ -208,8 +208,10 @@ if ! tail "${screenlog}" | grep -q "Thread Query Listener started"; then PrintToLog "warn" "server startup unsuccessful - perhaps query is disabled" "${screenlog}" fi -# execute server worker -./worker.sh & +# execute server worker if set to true +if [[ "${enabletasks}" == true ]]; then + nice -n 19 ./worker.sh & +fi # enables the watchdog script for backup integrity if [[ "${enablewatchdog}" == true ]]; then From 789f49663439e174132cc3c7c0f121c461398e2b Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 22:46:15 +0100 Subject: [PATCH 037/115] chore: script lock check now true by default --- server.settings | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.settings b/server.settings index 1bf4025..ca4d9ed 100644 --- a/server.settings +++ b/server.settings @@ -76,7 +76,7 @@ enabledebug="false" # enables debug log into logfiles if set to true date=$(date +"%Y-%m-%d %H:%M:%S") # defines format of script time logging # script lock check -skipscriptlockcheck="false" # scripts will not check for other already running scripts if set to true +skipscriptlockcheck="true" # scripts will not check for other already running scripts if set to true # change to server console after startup changetoconsole="replacechangetoconsole" # changes to server console after startup if set to true From dc988bc4db2057d2afe9555e99d0449bed5d818e Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 22:46:30 +0100 Subject: [PATCH 038/115] feat: added perform tasks listener --- server.functions | 83 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 65 insertions(+), 18 deletions(-) diff --git a/server.functions b/server.functions index e7a6743..a8fc261 100644 --- a/server.functions +++ b/server.functions @@ -338,21 +338,68 @@ function CreateCachedBackup { fi } + +# check for perform tasks string +function CheckPerformTasksString { + if tail -1 "${screenlog}" | grep -q "perform tasks"; then + player=$(tail -1 screen.log | grep -oP '.*?(?=perform tasks)' | 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 all available tasks of the server\"}]" + PrintToLog "info" "the player ${player} requested list of all tasks and has permission - server will list all tasks" "${screenlog}" + echo "" >> "${screenlog}" + # run perform tasks + if [[ "${enablesafetybackupstring}" == true ]]; then + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform backup is \"},{\"text\":\"enabled\",\"color\":\"green\"}]" + elif [[ "${enablesafetybackupstring}" == false ]]; then + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform backup is \"},{\"text\":\"disabled\",\"color\":\"red\"}]" + else + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform backup is \"},{\"text\":\"undefined\",\"color\":\"grey\"}]" + fi + if [[ "${enableconfirmrestartstring}" == true ]]; then + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform restart is \"},{\"text\":\"enabled\",\"color\":\"green\"}]" + elif [[ "${enableconfirmrestartstring}" == false ]]; then + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform restart is \"},{\"text\":\"disabled\",\"color\":\"red\"}]" + else + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform restart is \"},{\"text\":\"undefined\",\"color\":\"grey\"}]" + fi + if [[ "${enableconfirmupdatestring}" == true ]]; then + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform update is \"},{\"text\":\"enabled\",\"color\":\"green\"}]" + elif [[ "${enableconfirmupdatestring}" == false ]]; then + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform update is \"},{\"text\":\"disabled\",\"color\":\"red\"}]" + else + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform update is \"},{\"text\":\"undefined\",\"color\":\"grey\"}]" + fi + if [[ "${enableconfirmresetstring}" == true ]]; then + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform reset is \"},{\"text\":\"enabled\",\"color\":\"green\"}]" + elif [[ "${enableconfirmresetstring}" == false ]]; then + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform reset is \"},{\"text\":\"disabled\",\"color\":\"red\"}]" + else + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform reset is \"},{\"text\":\"undefined\",\"color\":\"grey\"}]" + fi + # spam protection + sleep 20s + else + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to request all available tasks of the server\"}]" + PrintToLog "warn" "the player ${player} requested a safety backup and does not have permission to do so" "${screenlog}" + echo "" >> "${screenlog}" + fi + 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 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 - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You successfully requested a safety backup of the server\"}]" - PrintToLog "info" "The player ${player} requested a safety backup and has permission - server will perform safety backup" "${backuplog}" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested a safety backup of the server\"}]" + PrintToLog "info" "the player ${player} requested a safety backup and has permission - server will perform safety backup" "${backuplog}" echo "" >> "${backuplog}" # run safety backup CreateCachedBackup "safety" # spam protection sleep 20s else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to safety backup the server\"}]" - PrintToLog "warn" "The player ${player} requested a safety backup and does not have permission to do so" "${backuplog}" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to safety backup the server\"}]" + PrintToLog "warn" "the player ${player} requested a safety backup and does not have permission to do so" "${backuplog}" echo "" >> "${backuplog}" fi fi @@ -363,12 +410,12 @@ function CheckConfirmRestartString { 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\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested a restart of the server\"}]" PrintToLog "info" "the player ${player} requested a restart and has permission - server will restart" "${screenlog}" ./restart.sh --quiet --now exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to restart the server\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to restart the server\"}]" PrintToLog "warn" "the player ${player} requested a restart and does not have permission to do so" "${screenlog}" fi fi @@ -376,12 +423,12 @@ function CheckConfirmRestartString { 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\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested a restart of the server\"}]" PrintToLog "info" "the player ${player} requested a restart and has permission - server will restart" "${screenlog}" ./restart.sh --quiet exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to restart the server\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to restart the server\"}]" PrintToLog "warn" "the player ${player} requested a restart and does not have permission to do so" "${screenlog}" fi fi @@ -392,12 +439,12 @@ function CheckConfirmUpdateString { 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\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested an update of the server\"}]" PrintToLog "info" "the player ${player} requested an update and has permission - server will update" "${screenlog}" ./update.sh --quiet --immediately exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to update the server\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to update the server\"}]" PrintToLog "warn" "the player ${player} requested an update and does not have permission to do so" "${screenlog}" fi fi @@ -405,12 +452,12 @@ function CheckConfirmUpdateString { 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\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested an update of the server\"}]" PrintToLog "info" "the player ${player} requested an update and has permission - server will update" "${screenlog}" ./update.sh --quiet exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to update the server\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to update the server\"}]" PrintToLog "warn" "the player ${player} requested an update and does not have permission to do so" "${screenlog}" fi fi @@ -421,12 +468,12 @@ function CheckConfirmResetString { 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\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested a reset of the server\"}]" PrintToLog "info" "the player ${player} requested a reset and has permission - server will reset" "${screenlog}" ./reset.sh --quiet --now exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to reset the server\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to reset the server\"}]" PrintToLog "warn" "the player ${player} requested a reset and does not have permission to do so" "${screenlog}" fi fi @@ -434,12 +481,12 @@ function CheckConfirmResetString { 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\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested a reset of the server\"}]" PrintToLog "info" "the player ${player} requested a reset and has permission - server will reset" "${screenlog}" ./reset.sh --quiet exit 0 else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"You do not have permissions to reset the server\"}]" + PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to reset the server\"}]" PrintToLog "warn" "the player ${player} requested a reset and does not have permission to do so" "${screenlog}" fi fi From 660c93562cbbceae6fa450bf8d308e5cac0e04dc Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 23:21:16 +0100 Subject: [PATCH 039/115] feat: perform tasks check --- worker.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/worker.sh b/worker.sh index 3753143..93836e7 100644 --- a/worker.sh +++ b/worker.sh @@ -79,6 +79,7 @@ while true; do if [[ ${enabletasks} == true ]]; then linebuffer=$(tail -1 "${screenlog}") if [[ ! ${linebuffer} == ${lastlinebuffer} ]]; then + CheckPerformTasksString if [[ ${enablesafetybackupstring} == true ]]; then # check if safety backup is enabled CheckSafetyBackupString fi From bd075e876bb685b4e830869a947c2ffba9c53a8e Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 23:21:38 +0100 Subject: [PATCH 040/115] fix: watchdog directory size compare --- worker.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/worker.sh b/worker.sh index 93836e7..6db8531 100644 --- a/worker.sh +++ b/worker.sh @@ -101,13 +101,13 @@ while true; do . ./server.settings timestamp=$(date +"%H:%M:%S") lasttimestamp=$(date -d -"2 minute" +"%H:%M:%S") - if [[ ${absoluteworldsize} < $((${lastabsoluteworldsize} - 65536)) ]]; then + if [[ ${absoluteworldsize} -lt $((${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 + if [[ ${absolutebackupsize} -lt $((${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}" From 5886c51a2812e7f8f11ce87c7a2291d004396c91 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 23:21:58 +0100 Subject: [PATCH 041/115] fix: autostart on crash for venting --- worker.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/worker.sh b/worker.sh index 6db8531..1d55162 100644 --- a/worker.sh +++ b/worker.sh @@ -120,7 +120,7 @@ while true; do fi # autostart on crash or exit if ! screen -list | grep -q "\.${servername}"; then - if [[ ${enablestartoncrash} == true ]]; then + if [[ ${enablestartoncrash} == true ]] && [[ -d "${serverdirectory}" ]]; then ./start.sh --quiet else exit 0 From 21a088d1c2958b533c951df58740f83fbdf62fe3 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 23:45:16 +0100 Subject: [PATCH 042/115] feat: added session lock error path --- start.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/start.sh b/start.sh index a5bc3f0..4a5cc3a 100644 --- a/start.sh +++ b/start.sh @@ -167,6 +167,11 @@ while [ ${startupchecks} -lt 120 ]; do PrintToLog "error" "server address is already in use - please change to another port" "${screenlog}" exit 1 fi + if tail -20 "${screenlog}" | grep -q "session.lock: already locked"; then + PrintToTerminal "error" "session is locked - is the world in use by another instance?" + PrintToLog "error" "session is locked - is the world in use by another instance?" "${screenlog}" + exit 1 + fi if ! screen -list | grep -q "${servername}"; then PrintToTerminal "fatal" "something went wrong - server appears to have crashed!" PrintToTerminal "info" "crash dump - last 10 lines of ${screenlog}" From 824043164e9d9e9a3a25a281547e00069d13afdb Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 23:49:32 +0100 Subject: [PATCH 043/115] fix: wait 20s before autostart on crash --- worker.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/worker.sh b/worker.sh index 1d55162..548683d 100644 --- a/worker.sh +++ b/worker.sh @@ -121,7 +121,10 @@ while true; do # autostart on crash or exit if ! screen -list | grep -q "\.${servername}"; then if [[ ${enablestartoncrash} == true ]] && [[ -d "${serverdirectory}" ]]; then - ./start.sh --quiet + sleep 20s + if ! screen -list | grep -q "\.${servername}"; then + ./start.sh --quiet + fi else exit 0 fi From dd3fe4982fdc021f1dbe362dd5234d3ecb842630 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 23:56:58 +0100 Subject: [PATCH 044/115] fix: exit if server already starting --- worker.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/worker.sh b/worker.sh index 548683d..8d7e4ca 100644 --- a/worker.sh +++ b/worker.sh @@ -124,6 +124,8 @@ while true; do sleep 20s if ! screen -list | grep -q "\.${servername}"; then ./start.sh --quiet + else + exit 0 fi else exit 0 From b1d798b83774b1b50b789a36f9af5d557931b3a5 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 28 Dec 2021 23:59:15 +0100 Subject: [PATCH 045/115] feat: worker script now checks if it is already running --- worker.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/worker.sh b/worker.sh index 8d7e4ca..f13b7c5 100644 --- a/worker.sh +++ b/worker.sh @@ -9,6 +9,11 @@ if [ $(id -u) = 0 ]; then exit 1 fi +# check if worker is already running +if pidof -x "worker.sh" &> /dev/null; then + exit 0 +fi + # read server.functions file with error checking if [[ -s "server.functions" ]]; then . ./server.functions From d69b87afc82acf747542936bb3071943edf545de Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Wed, 29 Dec 2021 00:01:40 +0100 Subject: [PATCH 046/115] fix: argument immediately was changed to now --- server.functions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.functions b/server.functions index a8fc261..716c199 100644 --- a/server.functions +++ b/server.functions @@ -441,7 +441,7 @@ function CheckConfirmUpdateString { if cat "ops.json" | grep -q "${player}"; then PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested an update of the server\"}]" PrintToLog "info" "the player ${player} requested an update and has permission - server will update" "${screenlog}" - ./update.sh --quiet --immediately + ./update.sh --quiet --now exit 0 else PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to update the server\"}]" From fa955398fa79471bb42020fa2c979016047fe315 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 16:11:15 +0100 Subject: [PATCH 047/115] feat: refactor and major overhaul of code base --- README.md | 146 +------- maintenance.sh | 84 ----- prerender.sh | 291 ---------------- reset.sh | 96 ++---- restart.sh | 86 ++--- server.functions | 848 ++++++++++++++++++++++++++-------------------- server.properties | 82 +++-- server.settings | 167 ++++----- start.sh | 271 +++++---------- stop.sh | 82 ++--- vent.sh | 137 +++----- worker.sh | 185 ++++------ 12 files changed, 862 insertions(+), 1613 deletions(-) delete mode 100644 maintenance.sh delete mode 100644 prerender.sh diff --git a/README.md b/README.md index 9f4ecee..ab06037 100644 --- a/README.md +++ b/README.md @@ -1,145 +1 @@ -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. -## 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 executable and executes the setup script. -``` -wget -q -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 pre-filled 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 amazing command line tool that creates a "virtual" terminal inside your terminal. - -You can view all your active screens by typing: `screen -list` -
-If you want to resume a certain screen session just type: `screen -r ${servername}` - -If you would like to scroll inside a screen session press Ctrl+A and Esc (enter copy mode).
-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. - -`whitelist add ${playername}` adding someone to your whitelist so he/she can join your server.
-`whitelist remove ${playername}` remove someone to your whitelist so he/she can no longer join your server.
-`op ${playername}` make someone admin on your server so he/she can execute commands.
-`deop ${playername}` remove admin permissions for a player so he/she can no longer execute commands.
-`ban ${playername}` ban someone from your server so he/she can no longer join your server.
-`pardon ${playername}` pardon someone from your server so he/she can join your server.
-`tp ${playername} ${x} ${y} ${z}` teleporting a player to cords.
-`tp ${playername} ${playername}` teleporting a player to another player. - -Important: If you do these commands in-game you will need to put a `/` before each 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. -# If you know what you are doing, feel free to tinker with them ;^) - -# command line 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)" -... -``` -## server.properties -If you would like to costomize your server further have a look at your server.properties file. -``` -nano server.properties -``` -Important settings are: - -`max-players=` (limits the maximum 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 in-game chunks 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 important 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 world-spawn only operators can touch)
-`pvp=` (ability for player to do damage to eachother) [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 -q` - -Arguments: `-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:
- -First star: Minutes [0 - 59]
-Secound star: Hours [0 - 23]
-Third star: Day of Month [0 - 31]
-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}/${script}.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. - -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 ;^) - -Best regards,
-Simylein +TODO: write new README diff --git a/maintenance.sh b/maintenance.sh deleted file mode 100644 index 3b55f8f..0000000 --- a/maintenance.sh +++ /dev/null @@ -1,84 +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 "$@" - -# check for script lock -CheckScriptLock - -# 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 - -# prints countdown to screen -PerformCountdown "going into maintenance" - -# server stop -PerformServerStop - -# awaits server stop -AwaitServerStop - -# force quit server if not stopped -ConditionalForceQuit - -# output confirmed stop -PrintToTerminal "ok" "server successfully stopped!" - -# create backup -CreateCachedBackup "maintenance" - -# 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 41ffbc6..0000000 --- a/prerender.sh +++ /dev/null @@ -1,291 +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 pre-render script" - -# parsing script arguments -ParseScriptArguments "$@" - -# check for script lock -CheckScriptLock - -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - PrintToTerminal "warn" "server is not currently running!" - exit 1 -fi - -# let user chose between online and offline prerendering -echo "would you like to startup online or offline pre-rendering?" -PS3="your choice: " -method=("online" "offline") -select method in "${method[@]}"; do - case $method in - "online") - PrintToTerminal "action" "starting online pre-renderer..." - - # explain to user - PrintToTerminal "info" "i will pre-render your minecraft world by teleporting a selected player through it" - PrintToTerminal "info" "i will scan so to speak in a grid with the spacing of 256 blocks" - - # ask for playername - read -p "please enter a player-name: " playername - echo "the player will be ${green}${playername}${nocolor}" - - # ask for cords - PS3="which radius would you like to pre-render? " - 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 - PrintToTerminal "info" "i would like to know how fast you want to scan your world" - PrintToTerminal "info" "i would recommend an interval of 20 to 80 seconds depending on your server resources" - PrintToTerminal "info" "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" - PrintToTerminal "info" "the selected grid will be ${green}${area}${nocolor}" - PrintToTerminal "info" "the selected interval will be ${green}${interval}${nocolor}" - PrintToTerminal "info" "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 pre-rendering" - 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 pre-renderer...${nocolor}" - else echo "${red}exiting...${nocolor}" - exit 1 - fi - - # prerender start - echo "pre-rendering 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} ~ ${z} 0 0" - ${between} - PrintToScreen "tp ${playername} ${x} ~ ${z} 90 0" - ${between} - PrintToScreen "tp ${playername} ${x} ~ ${z} 180 0" - ${between} - PrintToScreen "tp ${playername} ${x} ~ ${z} 270 0" - ${between} - counter=$((counter+1)) - done - done - - # command line finished message - PrintToScreen "say pre-rendering of your world has finished" - - # user info - PrintToTerminal "info" "pre-rendering of your world has finished" - PrintToTerminal "info" "rendered ${totalblocks} [${area}] blocks of area" - - # kick player with finished message - PrintToScreen "kick ${playername} pre-rendering of your world has finished" - break - ;; - "offline") - PrintToTerminal "action" "starting offline pre-renderer..." - - # explain to user - PrintToTerminal "info" "i will pre-render your minecraft world by setting the world-spawn to various coordinates and then restarting the server over and over" - PrintToTerminal "info" "i will scan so to speak in a grid with the spacing of 256 blocks" - - # ask for cords - PS3="Which radius would you like to pre-render? " - 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 resources" - 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 pre-render your world using world-spawns 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 pre-renderer...${nocolor}" - else echo "${red}exiting...${nocolor}" - exit 1 - fi - - # prerender start - PrintToTerminal "info" "pre-rendering started" - sleep 2s - - # teleport script with progress - totalamount=$((${amount} * ${amount})) - progress="1" - counting="1" - y="120" - for x in "${cords[@]}"; do - for z in "${cords[@]}"; do - let "progress=counting" - # progress counter - ProgressBar "${blue}[Script]${nocolor} Progress: [${progress}/${totalamount}]" "${progress}" "${totalamount}" - # setworldspawn to x y z - PrintToScreen "setworldspawn ${x} ~ ${z}" - # stop server - ./stop.sh --quiet --now - # start server - ./start.sh --quiet - done - done - - # reset spawnpoint - PrintToScreen "setworldspawn 0 ~ 0" - - # command line info - PrintToTerminal "ok" "pre-rendering of your world has finished" - break - ;; - *) echo "please choose an option from the list: " ;; - esac -done - -# log to debug if true -CheckDebug "executed pre-render script" - -# exit with code 0 -exit 0 diff --git a/reset.sh b/reset.sh index 4a8c01a..d6c1a8d 100644 --- a/reset.sh +++ b/reset.sh @@ -1,99 +1,59 @@ #!/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" +# safety checks +RootSafety +ScriptSafety + +# parse arguments +ParseArgs "$@" -# parsing script arguments -ParseScriptArguments "$@" +# debug +Debug "executing $0 script" -# check for script lock -CheckScriptLock +# change to server directory +ChangeServerDirectory -# write date to logfile -PrintToLog "action" "${date} executing reset 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 # prints countdown to screen -PerformCountdown "resetting the world" +Countdown "stopping" # server stop -PerformServerStop +Stop # awaits server stop -AwaitServerStop +AwaitStop # force quit server if not stopped -ConditionalForceQuit +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 -CreateCachedBackup "reset" +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}" +echo "action" "restarting server..." ./start.sh "$@" # 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 2274dc9..4c3bbfe 100644 --- a/restart.sh +++ b/restart.sh @@ -1,89 +1,51 @@ #!/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 +# safety checks +RootSafety +ScriptSafety -# 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 "$@" -# 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 script lock -CheckScriptLock - -# write date to logfile -PrintToLog "action" "${date} executing restart script" "${screenlog}" +# check for existance of executable +CheckExecutable -# check if server is running -if ! screen -list | grep -q "\.${servername}"; then - PrintToTerminal "warn" "server is not currently running!" - PrintToTerminal "action" "server not running - starting server now!" - PrintToLog "action" "server not running - starting server now!" "${screenlog}" - ./start.sh - exit 0 -fi +# look if server is running +CheckScreen # prints countdown to screen -PerformCountdown "restarting" +Countdown "restarting" # server stop -PerformServerStop +Stop # awaits server stop -AwaitServerStop +AwaitStop # force quit server if not stopped -ConditionalForceQuit +ForceQuit # output confirmed stop -PrintToLog "ok" "server successfully stopped!" "${screenlog}" -CheckQuiet "ok" "server successfully stopped!" +Log "ok" "server successfully stopped" "${screenLog}" +Print "ok" "server successfully stopped" # restart the server -CheckQuiet "action" "restarting server..." +Print "action" "restarting server..." ./start.sh "$@" # log to debug if true -CheckDebug "executed restart script" +Debug "executed $0 script" # exit with code 0 exit 0 diff --git a/server.functions b/server.functions index 716c199..e76f534 100644 --- a/server.functions +++ b/server.functions @@ -7,541 +7,671 @@ # please notice that editing these functions can be devastating # if you know what you are doing, feel free to tinker with them ;^) -# function for parsing arguments for a script -function ParseScriptArguments { - force=false - now=false - quiet=false - verbose=false - while [[ $# -gt 0 ]]; do - case "$1" in - -f) - force=true - ;; - -n) - now=true - ;; - -q) - quiet=true - ;; - -v) - verbose=true - ;; - --force) - force=true - ;; - --now) - now=true - ;; - --quiet) - quiet=true - ;; - --verbose) - verbose=true - ;; - *) - echo "info: bad argument: $1" - exit 1 - ;; - esac - shift - done -} - -# checks if a script is already running -function CheckScriptLock { - if [[ ${force} == false ]] && [[ ${skipscriptlockcheck} == false ]]; then - declare -a arr=("maintenance.sh" "prerender.sh" "reset.sh" "restart.sh" "restore.sh" "start.sh" "stop.sh" "update.sh" "vent.sh") - for i in "${scriptslock[@]}"; do - if pidof -x "${scriptslock[i]}" &> /dev/null; then - echo "info: script ${scriptslock[i]} is already running" - echo "info: use --force option to ignore safety check" - exit 1 - fi - done - fi -} - -# check if verbose mode is on -function CheckVerbose { - if [[ ${verbose} == true ]]; then - PrintToTerminal "${1}" "${2}" - fi -} -# checks if debug mode is on -function CheckDebug { - if [[ ${enabledebug} == true ]]; then - echo "$(date) ${1}" >> "debug.log" - fi -} -# check if quiet mode is on -function CheckQuiet { - if ! [[ ${quiet} == true ]]; then - PrintToTerminal "${1}" "${2}" - fi -} - -# prints all input to terminal -function PrintToTerminal { +# prints all input to log at given log level +function Log { if [[ $1 == "ok" ]]; then - echo "${green}ok: ${2}${nocolor}" + echo "${date} ok: ${2}" >>"${3}" fi if [[ $1 == "info" ]]; then - echo "${nocolor}info: ${2}${nocolor}" + echo "${date} info: ${2}" >>"${3}" fi if [[ $1 == "warn" ]]; then - echo "${yellow}warn: ${2}${nocolor}" + echo "${date} warn: ${2}" >>"${3}" fi if [[ $1 == "error" ]]; then - echo "${red}error: ${2}${nocolor}" + echo "${date} error: ${2}" >>"${3}" fi if [[ $1 == "fatal" ]]; then - echo "${red}fatal: ${2}${nocolor}" + echo "${date} fatal: ${2}" >>"${3}" fi if [[ $1 == "action" ]]; then - echo "${cyan}action: ${2}${nocolor}" + echo "${date} action: ${2}" >>"${3}" fi } -# prints all input to screen -function PrintToScreen { - if screen -list | grep -q "\.${servername}"; then - screen -Rd "${servername}" -X stuff "${1}$(printf '\r')" + +# prints all input to terminal at given log level +function Print { + if [[ ${1} == "ok" ]] && [[ ${quiet} == false ]]; then + echo "${time} ${green}ok${noColor}: ${2}" fi -} -# prints all input to log -function PrintToLog { - if [[ $1 == "ok" ]]; then - echo "ok: ${2}" >> "${3}" + if [[ ${1} == "info" ]] && [[ ${verbose} == true ]] && [[ ${quiet} == false ]]; then + echo "${time} ${blue}info${noColor}: ${2}" fi - if [[ $1 == "info" ]]; then - echo "info: ${2}" >> "${3}" + if [[ ${1} == "warn" ]]; then + echo "${time} ${yellow}warn${noColor}: ${2}" fi - if [[ $1 == "warn" ]]; then - echo "warn: ${2}" >> "${3}" + if [[ ${1} == "error" ]]; then + echo "${time} ${red}error${noColor}: ${2}" fi - if [[ $1 == "error" ]]; then - echo "error: ${2}" >> "${3}" + if [[ ${1} == "fatal" ]]; then + echo "${time} ${red}fatal${noColor}: ${2}" fi - if [[ $1 == "fatal" ]]; then - echo "fatal: ${2}" >> "${3}" + if [[ ${1} == "action" ]] && [[ ${quiet} == false ]]; then + echo "${time} ${cyan}action${noColor}: ${2}" fi - if [[ $1 == "action" ]]; then - echo "action: ${2}" >> "${3}" +} + +# checks if debug mode is on +function Debug { + if [[ ${enableDebug} == true ]]; then + echo "${date} ${1}" >>"${debugLog}" fi } -# prints success messages to terminal -function PrintToTerminalBackupSuccess { - PrintToTerminal "ok" "added ${backupdirectory}/hourly/${servername}-${1}.tar.gz" - PrintToTerminal "ok" "removed ${backupdirectory}/hourly/${servername}-${2}.tar.gz" - PrintToTerminal "ok" "current world size: ${worldsize}, current backup size: ${backupsize}, current disk space: ${diskspace}" - PrintToTerminal "ok" "time spent on backup process: ${timespent} milliseconds, compression ratio: ${compressedbackup}/${worldsize}" +# prints all input to screen +function Screen { + if screen -list | grep -q "\.${serverName}"; then + screen -Rd "${serverName}" -X stuff "${1}$(printf '\r')" + fi } -# prints success messages to screen -function PrintToScreenBackupSuccess { - PrintToScreen "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}\"}]}}}]" + +# 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 backup success to backup log -function PrintToLogBackupSuccess { - PrintToLog "ok" "added ${backupdirectory}/hourly/${servername}-${1}.tar.gz" "${backuplog}" - PrintToLog "ok" "removed ${backupdirectory}/hourly/${servername}-${2}.tar.gz" "${backuplog}" - PrintToLog "ok" "current world size: ${worldsize}, current backup size: ${backupsize}, current disk space: ${diskspace}" "${backuplog}" - PrintToLog "ok" "time spent on backup process: ${timespent} milliseconds, compression ratio: ${compressedbackup}/${worldsize}" "${backuplog}" - echo "" >> "${backuplog}" + +# checks if a script is already running +function ScriptSafety { + if [[ ${force} == false ]]; then + declare -a arr=("reset.sh" "restart.sh" "restore.sh" "start.sh" "stop.sh" "update.sh" "vent.sh") + for i in "${scriptslock[@]}"; do + if pidof -x "${scriptslock[i]}" &>/dev/null; then + Print "warn" "script ${scriptslock[i]} is already running" + Print "info" "use --force option to ignore this safety check" + exit 1 + fi + done + fi } -# prints backup already exists to terminal -function PrintToTerminalBackupAlreadyExists { - PrintToTerminal "error" "could not create new ${1}-backup - backup already exists" +# 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 already exists to screen -function PrintToScreenBackupAlreadyExists { - PrintToScreen "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\"}]}}}]" + +# check for existance of screen terminal +function LookForScreen { + if screen -list | grep -q "\.${serverName}"; then + Log "warn" "server is already running - type screen -r ${serverName} to open server terminal" >>"${screenLog}" + Print "warn" "server is already running" + exit 1 + fi } -# prints backup already exists to log -function PrintToLogBackupAlreadyExists { - PrintToLog "error" "could not create new ${1}-backup - backup already exists" "${backuplog}" - echo "" >> "${backuplog}" + +# check for executable +function CheckExecutable { + if ! ls ${serverfile}* 1>/dev/null 2>&1; then + Log "fatal" "no executable found" >>"${screenLog}" + Print "fatal" "no executable found" + exit 1 + fi } -# prints disk space warnig to terminal -function PrintToTerminalDiskSpaceWarning { - PrintToTerminal "warn" "free disk-space is getting rare - make some room for backups" +# 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 disk space warning to screen -function PrintToScreenDiskSpaceWarning { - PrintToScreen "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\"}]}}}]" + +# 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 disk space warning to log -function PrintToLogDiskSpaceWarning { - PrintToLog "warn" "free disk-space is getting rare - make some room for backups" "${backuplog}" - echo "" >> "${backuplog}" + +# 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 not enough disk space to terminal -function PrintToTerminalNotEnoughDiskSpace { - PrintToTerminal "error" "not enough disk-space to perform backup-${1}" +# 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 + -f) force=true ;; + -h) help=true ;; + -n) now=true ;; + -q) quiet=true ;; + -v) verbose=true ;; + --force) force=true ;; + --help) help=true ;; + --now) now=true ;; + --quiet) quiet=true ;; + --verbose) verbose=true ;; + *) + Print "warn" "bad argument: ${1}" + Print "info" "for help use --help" + ;; + esac + shift + done } -# prints not enough disk space to screen -function PrintToScreenNotEnoughtDiskSpace { - PrintToScreen "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\"}]}}}]" + +# 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 not enough disk space to backup log -function PrintToLogNotEnoughDiskSpace { - PrintToLog "error" "not enough disk-space to perform backup-${1}" "${backuplog}" - echo "" >> "${backuplog}" + +# 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 backup error to backup log -function PrintToTerminalBackupError { - PrintToTerminal "warn" "cannot remove old backup because new backup is missing" - PrintToTerminal "warn" "could not remove old backup" - PrintToTerminal "error" "could not backup world" +# 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 "ok" "current world size: ${worldSizeHuman}, current backup size: ${backupSizeHuman}, current disk space: ${diskspace}" "${backupLog}" + Log "ok" "time spent on backup process: ${timeSpent} milliseconds, compression ratio: ${compressedBackupSize}/${worldSizeHuman}" "${backupLog}" + + Print "ok" "added ${backupDirectory}/${1}/${serverName}-${2}.tar.gz" + Print "ok" "removed ${backupDirectory}/${1}/${serverName}-${3}.tar.gz" + Print "ok" "current world size: ${worldSizeHuman}, current backup size: ${backupSizeHuman}, current disk space: ${diskSpaceHuman}" + Print "ok" "time spent on backup process: ${timeSpent} milliseconds, compression ratio: ${compressedBackupSize}/${worldSizeHuman}" + + 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: ${backupSize}, current disk space: ${diskSpaceHuman}, time spent: ${timeSpent} ms, compression: ${compressedBackupSize}/${worldSizeHuman}" } -# prints error messages to screen -function PrintToScreenBackupError { - PrintToScreen "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\"}]}}}]" + +# 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}" + + Print "warn" "free disk-space is getting rare - make some room for backups" + + 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 backup error to log -function PrintToLogBackupError { - PrintToLog "warn" "cannot remove old backup because new backup is missing" "${backuplog}" - PrintToLog "warn" "could not remove old backup" "${backuplog}" - PrintToLog "error" "could not backup world" "${backuplog}" - echo "" >> "${backuplog}" + +# prints disk space error to terminal screen and backup log +function OutputDiskSpaceError { + Log "error" "not enough disk-space to perform backup-${1}" "${backupLog}" + + Print "error" "not enough disk-space to perform backup-${1}" + + TellrawBackup "fatal: not enough disk space - please immediately tell your server admin" "red" "could not create file: ${serverName}-${1}.tar.gz, could not remove file: ${serverName}-${2}.tar.gz, reason: not enough disk-space" } -# 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}%% " +# 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}" + + Print "error" "could not create new ${1}-backup - backup already exists" + + TellrawBackup "error: backup already exists - please tell your server admin" "red" "could not create file: ${serverName}-${1}.tar.gz, could not remove file: ${serverName}-${2}.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" + + TellrawBackup "fatal: could not create new backup - please immediately tell your server admin" "red" "could not create file: ${serverName}-${1}.tar.gz, could not remove file: ${serverName}-${2}.tar.gz, reason: tar reports errors during compression 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" + + TellrawBackup "fatal: could not create new backup - please immediately tell your server admin" "red" "could not create file: ${serverName}-${1}.tar.gz, could not remove file: ${serverName}-${2}.tar.gz, reason: generic error - missing directories, empty file-path 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 - PrintToLog "error" "the root-backupdirectory is missing - your backups are likely gone :(" "${backuplog}" - PrintToLog "info" "creating a new root-backupdirectory with name backups at ${serverdirectory}" "${backuplog}" - echo "" >> "${backuplog}" - PrintToTerminal "error" "the root-backupdirectory is missing - your backups are likely gone :(" - PrintToTerminal "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 - PrintToLog "warn" "the backup-directory ${backupcategories[${i}-1]} is missing" "${backuplog}" - PrintToLog "info" "creating ${backupdirectory}/${backupcategories[${i}-1]}" "${backuplog}" - echo "" >> "${backuplog}" - PrintToTerminal "warn" "the backup-directory ${backupcategories[${i}-1]} is missing" - PrintToTerminal "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 - PrintToTerminal "fatal" "Unable to connect to GitHub API. Script will exit! (maybe chose another branch?)" - exit 1 - else - CheckVerbose "info" "fetching file: ${1} from branch ${branch} on GitHub..." - wget -q -O "${1}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${1}" -fi -} +# 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 RemoveScriptsFromServerDirectory { - # user info about download - CheckVerbose "info" "removing scripts in serverdirectory..." +function RemoveScripts { # 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" "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]}" + for ((i = 1; i < ${scriptsLength} + 1; i++)); do + Print "info" "removing script ${scripts[${i} - 1]}" + rm "${scripts[${i} - 1]}" done } # function for downloading scripts from github -function DownloadScriptsFromGitHub { - # user info about download - CheckVerbose "info" "downloading scripts from GitHub..." +function DownloadScripts { # 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" "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]}" + for ((i = 0; i < ${scriptsLength}; i++)); do + Print "info" "downloading script ${scripts[${i}]} from branch ${branch} on github..." + wget -q -O "${scripts[${i}]}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${scripts[${i}]}" done } # function for making scripts executable -function MakeScriptsExecutable { +function ExecutableScripts { # 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" "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]} + for ((i = 0; i < ${scriptsLength}; i++)); do + Print "info" "setting script ${scripts[${i}]} executable" + chmod +x ${scripts[${i}]} done } -# function for creating a cached backup -function CreateCachedBackup { +# 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}-"* + if [[ -s "${backupDirectory}/cached/${1}-"* ]]; then + rm "${backupDirectory}/cached/${1}-"* fi - # create backup - CheckQuiet "action" "creating ${1} backup..." - tar -czf "world.tar.gz" "world" && mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/cached/${1}-${newdaily}-${newhourly}.tar.gz" + # user info about backup to create + Print "action" "creating cached ${1} backup..." + # create backup with given name + nice -n 19 cp -r "world" "tmp" + nice -n 19 tar -czf "world.tar.gz" "tmp" + nice -n 19 mv "${serverDirectory}/world.tar.gz" "${backupDirectory}/cached/${1}-${newDaily}-${newHourly}.tar.gz" + nice -n 19 rm -r "tmp" # check if safety backup exists - if ! [[ -s "${backupdirectory}/cached/${1}-${newdaily}-${newhourly}.tar.gz" ]]; then - # terminal output - PrintToTerminal "warn" "${1} backup failed" - # 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/${1}-${newdaily}-${newhourly}.tar.gz does not exist\"}]}}}]" - # logfile output - PrintToLog "warn" "${1} backup failed" "${backuplog}" - echo "" >> "${backuplog}" + 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 - # terminal output - CheckQuiet "ok" "${1} backup successful" - # 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/${1}-${newdaily}-${newhourly}.tar.gz\"}]}}}]" - # logfile output - PrintToLog "ok" "created ${backupdirectory}/cached/${1}-${newdaily}-${newhourly}.tar.gz as a ${1} backup" "${backuplog}" - echo "" >> "${backuplog}" + Log "warn" "${1} backup failed" "${backupLog}" + + Print "warn" "${1} backup failed" + + TellrawBackup "warn: backup failed" "yellow" "failed to create ${backupDirectory}/cached/${1}-${newDaily}-${newHourly}.tar.gz" fi } +# 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: admin contact info: ${adminContact}" + TellrawPlayer "${player}" "info: available commands: (seperated by comma)" + TellrawPlayer "${player}" "info: list tasks, list backups" + TellrawPlayer "${player}" "info: perform backup, perform restart, perform update, perform reset" + # spam protection + sleep 10s + fi +} -# check for perform tasks string -function CheckPerformTasksString { - if tail -1 "${screenlog}" | grep -q "perform tasks"; then - player=$(tail -1 screen.log | grep -oP '.*?(?=perform tasks)' | cut -d ' ' -f 4- | sed 's/.$//' | rev | sed 's/.$//' | rev | sed 's/.$//') +# 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 - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested all available tasks of the server\"}]" - PrintToLog "info" "the player ${player} requested list of all tasks and has permission - server will list all tasks" "${screenlog}" - echo "" >> "${screenlog}" - # run perform tasks - if [[ "${enablesafetybackupstring}" == true ]]; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform backup is \"},{\"text\":\"enabled\",\"color\":\"green\"}]" - elif [[ "${enablesafetybackupstring}" == false ]]; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform backup is \"},{\"text\":\"disabled\",\"color\":\"red\"}]" + 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 - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform backup is \"},{\"text\":\"undefined\",\"color\":\"grey\"}]" + TellrawPlayer "${player}" "perform backup is" "undefined" "grey" fi - if [[ "${enableconfirmrestartstring}" == true ]]; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform restart is \"},{\"text\":\"enabled\",\"color\":\"green\"}]" - elif [[ "${enableconfirmrestartstring}" == false ]]; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform restart is \"},{\"text\":\"disabled\",\"color\":\"red\"}]" + if [[ ${enablePerformRestart} == true ]]; then + TellrawPlayer "${player}" "perform restart is" "enabled" "green" + elif [[ "${enablePerformRestart}" == false ]]; then + TellrawPlayer "${player}" "perform restart is" "disabled" "red" else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform restart is \"},{\"text\":\"undefined\",\"color\":\"grey\"}]" + TellrawPlayer "${player}" "perform restart is" "undefined" "grey" fi - if [[ "${enableconfirmupdatestring}" == true ]]; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform update is \"},{\"text\":\"enabled\",\"color\":\"green\"}]" - elif [[ "${enableconfirmupdatestring}" == false ]]; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform update is \"},{\"text\":\"disabled\",\"color\":\"red\"}]" + if [[ ${enablePerformUpdate} == true ]]; then + TellrawPlayer "${player}" "perform update is" "enabled" "green" + elif [[ ${enablePerformUpdate} == false ]]; then + TellrawPlayer "${player}" "perform update is" "disabled" "red" else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform update is \"},{\"text\":\"undefined\",\"color\":\"grey\"}]" + TellrawPlayer "${player}" "perform update is" "undefined" "grey" fi - if [[ "${enableconfirmresetstring}" == true ]]; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform reset is \"},{\"text\":\"enabled\",\"color\":\"green\"}]" - elif [[ "${enableconfirmresetstring}" == false ]]; then - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform reset is \"},{\"text\":\"disabled\",\"color\":\"red\"}]" + if [[ ${enablePerformReset} == true ]]; then + TellrawPlayer "${player}" "perform reset is" "enabled" "green" + elif [[ ${enablePerformReset} == false ]]; then + TellrawPlayer "${player}" "perform reset is" "disabled" "red" else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"perform reset is \"},{\"text\":\"undefined\",\"color\":\"grey\"}]" + TellrawPlayer "${player}" "perform reset is" "undefined" "grey" fi # spam protection sleep 20s else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to request all available tasks of the server\"}]" - PrintToLog "warn" "the player ${player} requested a safety backup and does not have permission to do so" "${screenlog}" - echo "" >> "${screenlog}" + 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 } -# check for safety backup string -function CheckSafetyBackupString { - if tail -1 "${screenlog}" | grep -q "perform backup"; then + +# 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 + # spam protection + sleep 20s + 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 +} + +# 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 - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you successfully requested a safety backup of the server\"}]" - PrintToLog "info" "the player ${player} requested a safety backup and has permission - server will perform safety backup" "${backuplog}" - echo "" >> "${backuplog}" + 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 - CreateCachedBackup "safety" + CachedBackup "safety" # spam protection sleep 20s else - PrintToScreen "tellraw ${player} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"you do not have permissions to safety backup the server\"}]" - PrintToLog "warn" "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\"}]" - PrintToLog "info" "the player ${player} requested a restart and has permission - server will restart" "${screenlog}" + 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\"}]" - PrintToLog "warn" "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\"}]" - PrintToLog "info" "the player ${player} requested a restart and has permission - server will restart" "${screenlog}" + 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\"}]" - PrintToLog "warn" "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\"}]" - PrintToLog "info" "the player ${player} requested an update and has permission - server will update" "${screenlog}" + 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\"}]" - PrintToLog "warn" "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\"}]" - PrintToLog "info" "the player ${player} requested an update and has permission - server will update" "${screenlog}" + 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\"}]" - PrintToLog "warn" "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\"}]" - PrintToLog "info" "the player ${player} requested a reset and has permission - server will reset" "${screenlog}" + 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\"}]" - PrintToLog "warn" "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\"}]" - PrintToLog "info" "the player ${player} requested a reset and has permission - server will reset" "${screenlog}" + 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\"}]" - PrintToLog "warn" "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 } # performs countdown -function PerformCountdown { +function Countdown { if ! [[ ${now} == true ]]; then - counter="60" + counter=60 while [ ${counter} -gt 0 ]; do - if [[ "${counter}" =~ ^(60|40|20|10|5|4|3|2|1)$ ]];then - CheckQuiet "info" "server is ${1} in ${counter} seconds" - PrintToScreen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"server is ${1} in ${counter} seconds\"}]" + 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)) + counter=$((counter - 1)) sleep 1s done fi } -# performs a server stop -function PerformServerStop { - CheckQuiet "action" "stopping server..." - PrintToScreen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"stopping server...\"}]" +# 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 +} + +# 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 "${memory}" "${threads}" -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 - PrintToScreen "stop" + Screen "stop" } # awaits server stop -function AwaitServerStop { - stopchecks="0" - while [ $stopchecks -lt 30 ]; do - if ! screen -list | grep -q "\.${servername}"; then +function AwaitStop { + stopChecks=0 + while [ ${stopChecks} -lt 20 ]; do + if ! screen -list | grep -q "\.${serverName}"; then break fi - stopchecks=$((stopchecks+1)) - sleep 1; + stopChecks=$((stopChecks + 1)) + sleep 1 done } + # conditional force quit -function ConditionalForceQuit { - if screen -list | grep -q "${servername}"; then - PrintToTerminal "warn" "${servername} server still hasn't closed after 30 seconds, closing screen manually..." - PrintToLog "warn" "${servername} server still hasn't closed after 30 seconds, closing screen manually..." "${screenlog}" - screen -S "${servername}" -X 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 PrintGameOver { - echo "${red} ______ _____ ${nocolor}" - echo "${red} / _____) / ___ \ ${nocolor}" - echo "${red} | / ___ ____ ____ ____ | | | |_ _ ____ ____ ${nocolor}" - echo "${red} | | (___)/ _ | \ / _ ) | | | | | | / _ )/ ___) ${nocolor}" - echo "${red} | \____/( ( | | | | ( (/ / | |___| |\ V ( (/ /| | ${nocolor}" - echo "${red} \_____/ \_||_|_|_|_|\____) \_____/ \_/ \____)_| ${nocolor}" - echo "${red} ${nocolor}" +function GameOver { + 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 ca4d9ed..32adb55 100644 --- a/server.settings +++ b/server.settings @@ -4,107 +4,90 @@ # 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 +# your contact info for players +adminContact"i did not edit the server settings file /:" -# 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 +# 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") -# 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 +# server resource paths +serverName="replaceServerName" +homeDirectory="replaceHomeDirectory" +serverDirectory="replaceServerDirectory" +backupDirectory="replaceBackupDirectory" +executableServerFile="replaceExecutableServerFile" -# 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 +# script date and time logging +date=$(date +"%Y-%m-%d %H:%M:%S") +time=$(date +"%H:%M:%S") -# binarys -java="/usr/bin/java" # defines path to java binary -screen="/usr/bin/screen" # defines path to screen binary +# memory and threads for java server +memory="replacememx" +threads="replacethreadcount" -# 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 +# network publick and private addresses +public="replacePublic" +private="replacePrivate" -# github branch -branch="replacebranch" # all scripts will fetch from this branch +# values in bytes for disk space control +diskSpaceError="2097152" +diskSpaceWarning="8208608" -# 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 - -# script lock check -skipscriptlockcheck="true" # scripts will not check for other already running scripts if set to true +# logfile names +screenLog="screen.log" +backupLog="backup.log" +debugLog="debug.log" +# backup config +doHourly=true +doDaily=true +doWeekly=false +doMonthly=false + +# 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 "-18 days" +"%Y-%m-%d") +oldWeekly=$(date -d "-12 weeks" +"week-%U") +oldMonthly=$(date -d "-6 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 + +# github branch from whom scripts will fetch +branch="replaceBranch" +# enables or disable debug logging +enableDebug="replaceEnableDebug" # change to server console after startup -changetoconsole="replacechangetoconsole" # changes to server console after startup if set to true - +changeToConsole="replaceChangeToConsole" # enables watchdog integrity checks for backups -enablewatchdog="replaceenablewatchdog" # executes watchdog script if set to true - +enableBackupsWatchdog="replaceEnableBackupsWatchdog" # 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 - +enableWelcomeMessage="replaceEnableWelcomeMessage" # enables an autostart triggered by a server crash -enablestartoncrash="replaceenablestartoncrash" # let your server autostart in case of a crash - -# 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 +enableAutoStartOnCrash="replaceEnableAutoStartOnCrash" + +# 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/start.sh b/start.sh index 4a5cc3a..3c05eeb 100644 --- a/start.sh +++ b/start.sh @@ -1,254 +1,143 @@ #!/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 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 +# safety checks +RootSafety +ScriptSafety -# 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 "$@" -# 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 -# 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 - -# log to debug if true -CheckDebug "executing start script" - -# parsing script arguments -ParseScriptArguments "$@" - -# check for script lock -CheckScriptLock - -# padd logfile for visibility -echo "" >> "${screenlog}" -echo "" >> "${screenlog}" +# check for existance of executable +CheckExecutable -# write date to logfile -PrintToLog "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 - PrintToTerminal "warn" "server is already running! type screen -r ${servername} to open the console" - PrintToLog "warn" "server is already running! type screen -r ${servername} to open the console" "${screenlog}" - exit 1 -fi - -# check if interface is online -interfacechecks="0" -while [ ${interfacechecks} -lt 8 ]; do - if ping -c 1 "${interface}" &> /dev/null - then - CheckVerbose "ok" "interface is online" - PrintToLog "ok" "interface is online" "${screenlog}" - break - else - PrintToTerminal "warn" "interface is offline" - PrintToLog "warn" "interface is offline" "${screenlog}" - fi - if [ ${interfacechecks} -eq 7 ]; then - PrintToTerminal "error" "interface timed out" - PrintToLog "error" "interface timed out" "${screenlog}" - fi - sleep 1s - interfacechecks=$((interfacechecks+1)) -done +# check if private network is online +CheckPrivate -# check if dnsserver is online -networkchecks="0" -while [ ${networkchecks} -lt 8 ]; do - if ping -c 1 "${dnsserver}" &> /dev/null - then - CheckVerbose "ok" "nameserver is online" - PrintToLog "ok" "nameserver is online" "${screenlog}" - break - else - PrintToTerminal "warn" "nameserver is offline${nocolor}" - PrintToLog "warn" "nameserver is offline" "${screenlog}" - fi - if [ ${networkchecks} -eq 7 ]; then - PrintToTerminal "error" "nameserver timed out" - PrintToLog "error" "nameserver timed out" "${screenlog}" - fi - sleep 1s - networkchecks=$((networkchecks+1)) -done +# check if public network is online +CheckPublic # user information -CheckQuiet "info" "starting minecraft server. to view window type screen -r ${servername}." -CheckQuiet "info" "to minimise the window and let the server run in the background, press ctrl+a then ctrl+d" -PrintToLog "action" "starting ${servername} server..." "${screenlog}" -CheckVerbose "action" "starting ${servername} server..." +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 - PrintToTerminal "fatal" "something went wrong - server failed to start!" - PrintToLog "fatal" "something went wrong - server failed to start!" "${screenlog}" +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 -PrintToLog "ok" "server is on startup..." "${screenlog}" -CheckQuiet "ok" "server is on startup..." +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 "Thread Query Listener started"; then - PrintToLog "ok" "server startup successful - query up and running" "${screenlog}" - CheckQuiet "ok" "server startup successful - query up and running" +startupChecks="0" +while [ ${startupChecks} -lt 120 ]; do + if tail "${screenLog}" | grep -q "Thread Query Listener started"; then + Log "ok" "server startup successful - query up and running" "${screenLog}" + Print "ok" "server startup successful - query up and running" break fi - if tail -20 "${screenlog}" | grep -q "FAILED TO BIND TO PORT"; then - PrintToTerminal "error" "server port is already in use - please change to another port" - PrintToLog "error" "server port is already in use - please change to another port" "${screenlog}" + 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 - PrintToTerminal "error" "server address is already in use - please change to another port" - PrintToLog "error" "server address is already in use - please change to another port" "${screenlog}" + 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 - PrintToTerminal "error" "session is locked - is the world in use by another instance?" - PrintToLog "error" "session is locked - is the world in use by another instance?" "${screenlog}" + 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 - PrintToTerminal "fatal" "something went wrong - server appears to have crashed!" - PrintToTerminal "info" "crash dump - last 10 lines of ${screenlog}" - PrintToLog "fatal" "something went wrong - server appears to have crashed!" "${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 - PrintToTerminal "warn" "the server could be crashed" - PrintToLog "warn" "the server could be crashed" "${screenlog}" + 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 "Thread Query Listener started"; then - PrintToTerminal "warn" "server startup unsuccessful - perhaps query is disabled" - PrintToLog "warn" "server startup unsuccessful - perhaps query is disabled" "${screenlog}" -fi - -# execute server worker if set to true -if [[ "${enabletasks}" == true ]]; then - nice -n 19 ./worker.sh & +if ! tail "${screenLog}" | grep -q "Thread Query Listener started"; then + Log "warn" "server startup unsuccessful - perhaps query is disabled" "${screenLog}" + Print "warn" "server startup unsuccessful - perhaps query is disabled" fi -# enables the watchdog script for backup integrity -if [[ "${enablewatchdog}" == true ]]; then - CheckVerbose "info" "activating watchdog..." -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..." +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..." +if [[ "${enableWelcomeMessage}" == true ]]; then + Print "info" "activating welcome messages..." fi - -# check if user wants to enable task execution -if [[ "${enablestartoncrash}" == true ]]; then - CheckVerbose "info" "activating auto start on crash..." +if [[ "${enableAutoStartOnCrash}" == true ]]; then + Print "info" "activating auto start on crash..." fi - -# if set to true change automatically to server console -if [[ "${changetoconsole}" == true ]]; then - CheckVerbose "info" "changing to server console..." - screen -r "${servername}" +if [[ "${changeToConsole}" == true ]]; then + Print "info" "changing to server console..." + screen -r "${serverName}" fi -# user information -CheckQuiet "info" "if you would like to change to server console - type screen -r ${servername}" +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 a45e6f1..31c3e30 100644 --- a/stop.sh +++ b/stop.sh @@ -1,83 +1,47 @@ #!/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 +# safety checks +RootSafety +ScriptSafety -# 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 "$@" -# 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 "$@" - -# check for script lock -CheckScriptLock - -# write date to logfile -PrintToLog "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 # prints countdown to screen -PerformCountdown "stopping" +Countdown "stopping" # server stop -PerformServerStop +Stop # awaits server stop -AwaitServerStop +AwaitStop # force quit server if not stopped -ConditionalForceQuit +ForceQuit # output confirmed stop -PrintToLog "ok" "server successfully stopped!" "${screenlog}" -CheckQuiet "ok" "server successfully stopped!" +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/vent.sh b/vent.sh index 23bb388..e473b6b 100644 --- a/vent.sh +++ b/vent.sh @@ -3,133 +3,72 @@ # 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 +# safety checks +RootSafety +ScriptSafety -# 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 "$@" -# 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 script" -# log to debug if true -CheckDebug "executing vent script" +# change to server directory +ChangeServerDirectory -# parsing script arguments -ParseScriptArguments "$@" +# check for existance of executable +CheckExecutable -# check for script lock -CheckScriptLock +# look if server is running +CheckScreen # user safety function for confirmation -PrintToTerminal "warn" "are you sure you want to vent your server?" -read -p "if so, please type ${red}confirm venting${nocolor} " +Print "warn" "are you sure you want to vent your server?" +read -p "if so, please type ${red}confirm venting${noColor} " if [[ ${REPLY} == "confirm venting" ]]; then - PrintToTerminal "info" "user confirmed venting - server will self-destruct now" + Print "info" "you confirmed venting - server will self-destruct now" else - PrintToTerminal "error" "wrong token - please try again" + Print "error" "wrong token - please try again" exit 1 fi -# write date to logfile -PrintToLog "action" "${date} executing self-destruct script" "${screenlog}" - -# warning -PrintToTerminal "action" "self-destructing server" -PrintToScreen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"self-destructing server\",\"color\":\"red\"}]" - -# sleep for 2 seconds -sleep 2s - -# check if now is specified -if ! [[ ${now} == 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}" - PrintToScreen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"server is self-destructing in ${counter} seconds\",\"color\":\"red\"}]" - 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}" -PrintToScreen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"GAME OVER\",\"color\":\"red\"}]" - -# sleep 2 seconds -sleep 2s - -# check if server is running -if screen -list | grep -q "\.${servername}"; then +Screen "tellraw @a [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"GAME OVER\",\"color\":\"red\"}]" - # server stop - PerformServerStop +# server stop +Stop - # awaits server stop - AwaitServerStop +# awaits server stop +AwaitStop - # force quit server if not stopped - ConditionalForceQuit +# force quit server if not stopped +ForceQuit - # output confirmed stop - PrintToLog "ok" "server successfully stopped!" "${screenlog}" - CheckQuiet "ok" "server successfully stopped!" - -fi - -# sleep 2 seconds -sleep 2s - -cd "${homedirectory}" +cd "${homeDirectory}" # remove crontab crontab -r # remove serverdirectory -echo "deleting server..." -rm -r "${servername}" +Print "info" "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 - PrintToTerminal "error" "venting failed!" + Print "error" "venting failed!" exit 1 fi +# debug +Debug "executed $0 script" + # exit with code 0 exit 0 diff --git a/worker.sh b/worker.sh index f13b7c5..e3daf85 100644 --- a/worker.sh +++ b/worker.sh @@ -1,143 +1,86 @@ #!/bin/bash - # minecraft server worker script -# is meant to be executed detached with ./worker.sh & by start.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 - -# check if worker is already running -if pidof -x "worker.sh" &> /dev/null; then - exit 0 -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 +# 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 +# parse arguments +ParseArgs "$@" -# 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 -# write a function that checks if backups are done regularly -# if any irregularities are detected notify via ingame or logfiles -# 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" ) -linebuffer=$(tail -1 "${screenlog}") -lastabsolutebackupsize="65536" -lastabsoluteworldsize="65536" -lastlinebuffer="${linebuffer}" -counter="0" +# run various functions every second until server exits +counter=0 while true; do - # welcome messages - if [[ ${welcomemessage} == true ]]; then - 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 - fi - # admin tasks - if [[ ${enabletasks} == true ]]; then - linebuffer=$(tail -1 "${screenlog}") - if [[ ! ${linebuffer} == ${lastlinebuffer} ]]; then - CheckPerformTasksString - if [[ ${enablesafetybackupstring} == true ]]; then # check if safety backup is enabled - CheckSafetyBackupString - fi - if [[ ${enableconfirmrestartstring} == true ]]; then # check if safety backup is enabled - CheckConfirmRestartString - fi - if [[ ${enableconfirmupdatestring} == true ]]; then # check if safety backup is enabled - CheckConfirmUpdateString - fi - if [[ ${enableconfirmresetstring} == true ]]; then # check if safety backup is enabled - CheckConfirmResetString + 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 - linebuffer=$(tail -1 "${screenlog}") # store last line of screen log into buffer + + Help + ListTasks + ListBackups + if [[ ${enablePerformBackup} == true ]]; then + PerformBackup + fi + if [[ ${enablePerformRestart} == true ]]; then + PerformRestart + fi + if [[ ${enablePerformUpdate} == true ]]; then + PerformUpdate + fi + if [[ ${enablePerformReset} == true ]]; then + PerformReset + fi fi - # watchdog - if [[ ${enablewatchdog} == true ]]; then + + if [[ ${enableBackupsWatchdog} == true ]]; then if [[ ${counter} -eq 120 ]]; then - . ./server.settings - timestamp=$(date +"%H:%M:%S") - lasttimestamp=$(date -d -"2 minute" +"%H:%M:%S") - if [[ ${absoluteworldsize} -lt $((${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} + 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 [[ ${absolutebackupsize} -lt $((${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} + 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 - lastabsoluteworldsize="${absoluteworldsize}" - lastabsolutebackupsize="${absolutebackupsize}" - counter="0" + lastWorldSizeBytes=${worldSizeBytes} + lastBackupSizeBytes=${backupSizeBytes} + counter=0 fi fi - # autostart on crash or exit - if ! screen -list | grep -q "\.${servername}"; then - if [[ ${enablestartoncrash} == true ]] && [[ -d "${serverdirectory}" ]]; then - sleep 20s - if ! screen -list | grep -q "\.${servername}"; then - ./start.sh --quiet - else - exit 0 - fi - else - exit 0 - fi + + if ! screen -list | grep -q "\.${serverName}"; then + Debug "executed $0 script" + exit 0 fi - # variables - lastlinebuffer="${linebuffer}" - counter=$((counter+1)) + + lastLineBuffer="${lineBuffer}" + counter++ sleep 1s done From 2edc9501e1164f26b3d0722703f4c9a8601b732e Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:14:40 +0100 Subject: [PATCH 048/115] feat: better backup script --- backup.sh | 513 ++++++++--------------------------------------- server.functions | 389 ++++++++++++++++++----------------- server.settings | 8 +- setup.sh | 472 ++++++++++++++++++------------------------- 4 files changed, 491 insertions(+), 891 deletions(-) diff --git a/backup.sh b/backup.sh index 0a373c1..df5b6a7 100644 --- a/backup.sh +++ b/backup.sh @@ -1,469 +1,130 @@ #!/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.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 files +source server.settings +source server.functions -# 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 +# safety checks +RootSafety +ScriptSafety -# parsing script arguments -ParseScriptArguments "$@" +# parse backup category +ParseCategory "$@" -# test if all categories for backups exists if not create them -CheckBackupDirectoryIntegrity +# parse arguments +ParseArgs "$@" +# 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 - PrintToLog "action" "${date} executing backup-hourly script" "${screenlog}" - PrintToLog "action" "${date} executing backup-hourly script" "${backuplog}" - CheckDebug "executing backup-hourly script" +# check if server is running +CheckScreen - # start milliseconds timer - before=$(date +%s%3N) +# test all categories +BackupDirectoryIntegrity - # checks for the existence of a screen terminal - if ! screen -list | grep -q "\.${servername}"; then - PrintToTerminal "warn" "server is not currently running!" - PrintToLog "info" "server is not currently running!" "${screenlog}" - PrintToLog "info" "server is not currently running!" "${backuplog}" - echo "" >> "${backuplog}" +# main backup function +function RunBackup { + Debug "executing backup-${1} script" + if (((${worldSizeBytes} + ${diskSpaceError}) > ${diskSpaceBytes})); then + OutputDiskSpaceError "${1}" "${2}" "${3}" + Debug "backup script reports not enough disk-space while performing backup-${1}" exit 1 fi - - # 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" - exit 1 + if (((${worldSizeBytes} + ${diskSpaceWarning}) > ${diskSpaceBytes})); then + OutputDiskSpaceWarning + Debug "backup script reports low disk-space while performing backup-${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 - # disable auto save - PrintToScreen "save-off" - # run backup with compression + if ! [[ -s "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" ]]; then + Screen "save-off" + sleep 1s + before=$(date +%s%3N) nice -n 19 cp -r "world" "tmp" nice -n 19 tar -czf "world.tar.gz" "tmp" - # check for tar errors - if [ "$?" != 0 ]; then - CheckDebug "backup script reports tar error while performing backup-hourly" + if [ $? != 0 ]; then + OutputBackupTarError "${2}" "${3}" + Debug "backup script reports tar error while performing backup-${1}" fi - nice -n 19 mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/hourly/${servername}-${newhourly}.tar.gz" + nice -n 19 mv "${serverDirectory}/world.tar.gz" "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" nice -n 19 rm -r "tmp" - # enable auto save - PrintToScreen "save-on" + after=$(date +%s%3N) + Screen "save-on" + sleep 1s + timeSpent=$((${after} - ${before})) else - PrintToTerminalBackupAlreadyExists "hourly" - PrintToScreenBackupAlreadyExists "${newhourly}" "${oldhourly}" - PrintToLogBackupAlreadyExists "hourly" - CheckDebug "backup script reports backup already exists while performing backup-hourly" + OutputBackupAlreadyExists "${1}" "${2}" "${3}" + Debug "backup script reports backup already exists while performing backup-${1}" 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" + if [[ -s "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" ]]; then + if [[ -s "${backupDirectory}/${1}/${serverName}-${3}.tar.gz" ]]; then + nice -n 19 rm "${backupDirectory}/${1}/${serverName}-${3}.tar.gz" + fi + compressedBackupSize=$(du -sh ${backupDirectory}/${1}/${serverName}-${2}.tar.gz | cut -f1) + source server.settings + OutputBackupSuccess "${1}" "${2}" "${3}" + Debug "backup script reports backup success while performing backup-${1}" else - # ingame and logfile error output - PrintToScreenBackupError "${newhourly}" "${oldhourly}" - PrintToLogBackupError - PrintToTerminalBackupError - CheckDebug "backup script reports backup error while performing backup-hourly" + OutputBackupGenericError "${2}" "${3}" + Debug "backup script reports backup error while performing backup-${1}" + fi + Debug "executed backup-${1} script" +} + +# hourly backup +if [ ${isHourly} == true ]; then + if [ ${doHourly} == true ]; then + # run backup + RunBackup "hourly" "${newHourly}" "${oldHourly}" + else + Log "info" "backup-hourly is disabled" "${backupLog}" + Print "info" "backup-hourly is disabled" fi - -else - # write to logfiles that it's disabled - CheckDebug "backup-hourly is disabled" - PrintToLog "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 - PrintToLog "action" "${date} executing backup-daily script" "${screenlog}" - PrintToLog "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 - before=$(date +%s%3N) - - # checks for the existence of a screen terminal - if ! screen -list | grep -q "\.${servername}"; then - PrintToTerminal "warn" "server is not currently running!" - PrintToLog "info" "server is not currently running!" "${screenlog}" - PrintToLog "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 "${newdaily}" "${olddaily}" - PrintToLogNotEnoughDiskSpace "daily" - PrintToTerminalNotEnoughDiskSpace "daily" - CheckDebug "backup script reports not enough disk-space while performing backup-daily" - 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 - # disable auto save - PrintToScreen "save-off" - # run backup with compression - nice -n 19 cp -r "world" "tmp" - nice -n 19 tar -czf "world.tar.gz" "tmp" - # check for tar errors - if [ "$?" != 0 ]; then - CheckDebug "backup script reports tar error while performing backup-daily" - fi - nice -n 19 mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/daily/${servername}-${newdaily}.tar.gz" - nice -n 19 rm -r "tmp" - # enable auto save - PrintToScreen "save-on" - else - PrintToTerminalBackupAlreadyExists "daily" - PrintToScreenBackupAlreadyExists "${newdaily}" "${olddaily}" - PrintToLogBackupAlreadyExists "daily" - CheckDebug "backup script reports backup already exists while performing backup-daily" - 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" - 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 "backup-daily is disabled" - PrintToLog "info" "backup-daily is disabled" "${backuplog}" - echo "" >> "${backuplog}" + Log "info" "backup-daily is disabled" "${backupLog}" + Print "info" "backup-daily 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 - PrintToLog "action" "${date} executing backup-weekly script" "${screenlog}" - PrintToLog "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 - PrintToTerminal "warn" "server is not currently running!" - PrintToLog "info" "server is not currently running!" "${screenlog}" - PrintToLog "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 - # disable auto save - PrintToScreen "save-off" - # run backup with compression - nice -n 19 cp -r "world" "tmp" - nice -n 19 tar -czf "world.tar.gz" "tmp" - # check for tar errors - if [ "$?" != 0 ]; then - CheckDebug "backup script reports tar error while performing backup-weekly" - fi - nice -n 19 mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/weekly/${servername}-${newweekly}.tar.gz" - nice -n 19 rm -r "tmp" - # enable auto save - PrintToScreen "save-on" - else - PrintToTerminalBackupAlreadyExists "weekly" - PrintToScreenBackupAlreadyExists "${newweekly}" "${oldweekly}" - PrintToLogBackupAlreadyExists "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 - +# weekly backup +if [ ${isWeekly} == true ]; then + if [ ${doWeekly} == true ]; then + # run backup + RunBackup "weekly" "${newWeekly}" "${oldWeekly}" else - # write to logfiles that it's disabled - CheckDebug "backup-weekly is disabled" - PrintToLog "info" "backup-weekly is disabled" "${backuplog}" - echo "" >> "${backuplog}" + 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 - PrintToLog "action" "${date} executing backup-monthly script" "${screenlog}" - PrintToLog "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 - PrintToTerminal "warn" "server is not currently running!" - PrintToLog "info" "server is not currently running!" "${screenlog}" - PrintToLog "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 - # disable auto save - PrintToScreen "save-off" - # run backup with compression - nice -n 19 cp -r "world" "tmp" - nice -n 19 tar -czf "world.tar.gz" "tmp" - # check for tar errors - if [ "$?" != 0 ]; then - CheckDebug "backup script reports tar error while performing backup-monthly" - fi - nice -n 19 mv "${serverdirectory}/world.tar.gz" "${backupdirectory}/monthly/${servername}-${newmonthly}.tar.gz" - nice -n 19 rm -r "tmp" - # enable auto save - PrintToScreen "save-on" - else - PrintToTerminalBackupAlreadyExists "monthly" - PrintToScreenBackupAlreadyExists "${newmonthly}" "${oldmonthly}" - PrintToLogBackupAlreadyExists "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 "backup-monthly is disabled" - PrintToLog "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/server.functions b/server.functions index e76f534..9e3b826 100644 --- a/server.functions +++ b/server.functions @@ -65,6 +65,78 @@ function Screen { fi } +# 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 + -f) force=true ;; + -h) help=true ;; + -n) now=true ;; + -q) quiet=true ;; + -v) verbose=true ;; + --force) force=true ;; + --help) help=true ;; + --now) now=true ;; + --quiet) quiet=true ;; + --verbose) verbose=true ;; + *) + Print "warn" "bad argument: ${1}" + Print "info" "for help use --help" + ;; + esac + shift + done +} + +function ParseCategory { + # standart values + isHourly=false + isDaily=false + isWeekly=false + isMonthly=false + # test and set backup category + if [[ $1 == "hourly" ]]; then + isHourly=true + shift + elif [[ $1 == "hourly" ]]; then + isDaily=true + shift + elif [[ $1 == "hourly" ]]; then + isWeekly=true + shift + elif [[ $1 == "hourly" ]]; then + isMonthly=true + shift + else + Print "error" "$1 is not a backup category" + shift + fi +} + +# 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 @@ -141,31 +213,139 @@ function TellrawPlayer { fi } -# 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 - -f) force=true ;; - -h) help=true ;; - -n) now=true ;; - -q) quiet=true ;; - -v) verbose=true ;; - --force) force=true ;; - --help) help=true ;; - --now) now=true ;; - --quiet) quiet=true ;; - --verbose) verbose=true ;; - *) - Print "warn" "bad argument: ${1}" - Print "info" "for help use --help" - ;; - esac - shift +# 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 +} + +# 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 "${memory}" "${threads}" -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 + for ((i = 1; i < ${scriptsLength} + 1; i++)); do + Print "info" "removing script ${scripts[${i} - 1]}" + rm "${scripts[${i} - 1]}" + done +} + +# function for downloading scripts from github +function DownloadScripts { + # downloading scripts from github + # loop through all entries in the array + for ((i = 0; i < ${scriptsLength}; i++)); do + Print "info" "downloading script ${scripts[${i}]} from branch ${branch} on github..." + wget -q -O "${scripts[${i}]}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${scripts[${i}]}" + done +} + +# function for making scripts executable +function ExecutableScripts { + # make selected scripts executable + # loop through all entries in the array + for ((i = 0; i < ${scriptsLength}; i++)); do + Print "info" "setting script ${scripts[${i}]} executable" + chmod +x ${scripts[${i}]} done } @@ -221,7 +401,7 @@ function OutputDiskSpaceError { Print "error" "not enough disk-space to perform backup-${1}" - TellrawBackup "fatal: not enough disk space - please immediately tell your server admin" "red" "could not create file: ${serverName}-${1}.tar.gz, could not remove file: ${serverName}-${2}.tar.gz, reason: not enough disk-space" + 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 already exists messages to terminal screen and backup log @@ -230,7 +410,7 @@ function OutputBackupAlreadyExists { Print "error" "could not create new ${1}-backup - backup already exists" - TellrawBackup "error: backup already exists - please tell your server admin" "red" "could not create file: ${serverName}-${1}.tar.gz, could not remove file: ${serverName}-${2}.tar.gz, reason: backup already exists" + 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 @@ -280,41 +460,6 @@ function BackupDirectoryIntegrity { done } -# 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 - for ((i = 1; i < ${scriptsLength} + 1; i++)); do - Print "info" "removing script ${scripts[${i} - 1]}" - rm "${scripts[${i} - 1]}" - done -} - -# function for downloading scripts from github -function DownloadScripts { - # downloading scripts from github - # loop through all entries in the array - for ((i = 0; i < ${scriptsLength}; i++)); do - Print "info" "downloading script ${scripts[${i}]} from branch ${branch} on github..." - wget -q -O "${scripts[${i}]}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${scripts[${i}]}" - done -} - -# function for making scripts executable -function ExecutableScripts { - # make selected scripts executable - # loop through all entries in the array - for ((i = 0; i < ${scriptsLength}; i++)); do - Print "info" "setting script ${scripts[${i}]} executable" - chmod +x ${scripts[${i}]} - done -} - # function for creating a cached backup with name as input function CachedBackup { # remove all older cached backups @@ -555,123 +700,3 @@ function PerformReset { fi fi } - -# 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 -} - -# 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 -} - -# 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 "${memory}" "${threads}" -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}" -} diff --git a/server.settings b/server.settings index 32adb55..ea50ebc 100644 --- a/server.settings +++ b/server.settings @@ -5,7 +5,7 @@ # if you know what you are doing, feel free to tinker with them ;^) # your contact info for players -adminContact"i did not edit the server settings file /:" +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") @@ -22,10 +22,10 @@ date=$(date +"%Y-%m-%d %H:%M:%S") time=$(date +"%H:%M:%S") # memory and threads for java server -memory="replacememx" -threads="replacethreadcount" +memory="replaceMemory" +threads="replaceThreads" -# network publick and private addresses +# network public and private addresses public="replacePublic" private="replacePrivate" diff --git a/setup.sh b/setup.sh index 761e21d..d529164 100644 --- a/setup.sh +++ b/setup.sh @@ -19,52 +19,64 @@ blue="$(tput setaf 4)" magenta="$(tput setaf 5)" cyan="$(tput setaf 6)" white="$(tput setaf 7)" -nocolor="$(tput sgr0)" +noColor="$(tput sgr0)" -# prints all input to terminal -function PrintToTerminal { - if [[ $1 == "ok" ]]; then - echo "${green}ok: ${2}${nocolor}" +# prints all input to terminal at given log level +function Print { + if [[ ${1} == "ok" ]]; then + echo "${time} ${green}ok${noColor}: ${2}" fi - if [[ $1 == "info" ]]; then - echo "${nocolor}info: ${2}${nocolor}" + if [[ ${1} == "info" ]]; then + echo "${time} ${blue}info${noColor}: ${2}" fi - if [[ $1 == "warn" ]]; then - echo "${yellow}warn: ${2}${nocolor}" + if [[ ${1} == "warn" ]]; then + echo "${time} ${yellow}warn${noColor}: ${2}" fi - if [[ $1 == "error" ]]; then - echo "${red}error: ${2}${nocolor}" + if [[ ${1} == "error" ]]; then + echo "${time} ${red}error${noColor}: ${2}" fi - if [[ $1 == "fatal" ]]; then - echo "${red}fatal: ${2}${nocolor}" + if [[ ${1} == "fatal" ]]; then + echo "${time} ${red}fatal${noColor}: ${2}" fi - if [[ $1 == "action" ]]; then - echo "${cyan}action: ${2}${nocolor}" + if [[ ${1} == "action" ]]; then + echo "${time} ${cyan}action${noColor}: ${2}" fi } -# root safety check -if [ $(id -u) = 0 ]; then - PrintToTerminal "fatal" "please do not run me as root :( - this is dangerous!" - exit 1 -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 Linux -function CheckForLinux { +function CheckLinux { if [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then # inform user about Linux - PrintToTerminal "ok" "you are running Linux as your operating system - your server will likely run!" + 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 - PrintToTerminal "warn" "your system has less than 2.56 GB of memory - this may impact server performance!" + 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 - PrintToTerminal "warn" "your system has less than 4 threads - this may impact server performance!" + if ((${threads} < 4)); then + Print "warn" "your system has less than 4 threads - this may impact server performance!" fi supported=true else @@ -73,21 +85,21 @@ function CheckForLinux { } # check for macOS -function CheckForMacOS { +function CheckMacOS { if [ "$(uname)" == "Darwin" ]; then # inform user about macOS - PrintToTerminal "warn" "you are running macOS as your operating system - your server may not run!" + 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 - PrintToTerminal "warn" "your system has less than 2.56 GB of memory - this may impact server performance!" + 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 - PrintToTerminal "warn" "your system has less than 4 threads - this may impact server performance!" + if ((${threads} < 4)); then + Print "warn" "your system has less than 4 threads - this may impact server performance!" fi supported=true else @@ -96,356 +108,258 @@ function CheckForMacOS { } # check for Windows -function CheckForWindows { +function CheckWindows { if [ "$(expr substr $(uname -s) 1 10)" == "MINGW64_NT" ]; then - # inform user about Windows - PrintToTerminal "fatal" "you are running Windows as your operating system - your server will not run!" - supported=false - exit 1 + # inform user about Windows + Print "fatal" "you are running Windows as your operating system - your server will not run!" + supported=false + exit 1 fi } # check for unsupported OS -function CheckForUnsupportedOS { +function CheckUnsupported { if [ supported == false ]; then # inform user about unsupported operating system - PrintToTerminal "fatal" "you are running an unsupported operating system - your server will not run!" + Print "fatal" "you are running an unsupported operating system - your server will not run!" exit 1 fi } -# run all checks -CheckForLinux -CheckForMacOS -CheckForWindows -CheckForUnsupportedOS - -# 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 = 0; i < ${packageslength}; i ++ )); do - if ! command -v ${packages[$i-1]} &> /dev/null; then - PrintToTerminal "fatal" "the package ${packages[${i}]} is not installed on your system" - exit 1 +# 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" + Print "ok" "download successful" + if ! [[ -s "minecraft-server.${version}.jar" ]]; then + Print "fatal" "downloaded server-file minecraft-server.${version}.jar is empty or not available" fi -done +} + +# root safety check +if [ $(id -u) = 0 ]; then + Print "fatal" "please do not run me as root :( - this is dangerous!" + exit 1 +fi + +# run all checks +CheckLinux +CheckMacOS +CheckWindows +CheckUnsupported # user info about script -PrintToTerminal "action" "i will setup a minecraft server for you ;^)" +Print "action" "i will setup a minecraft server for you ;^)" # initial question -read -re -i "minecraft" -p "how should I call your server? your name: " servername +read -re -i "minecraft" -p "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 "prompt: please enter a serverName which only contains letters and numbers: " serverName else - regexcheck="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 "prompt: directory ${serverName} already exists - please enter another directory: " serverName else - existscheck="true" + existsCheck=true fi - if [[ ${regexcheck} == "true" ]] && [[ ${existscheck} == "true" ]]; then + if [[ ${regexCheck} == true ]] && [[ ${existsCheck} == true ]]; then verify=true else - verify="false" + verify=false fi done -PrintToTerminal "info" "your server will be called ${green}${servername}${nocolor}" +Print "info" "your server will be called ${green}${serverName}${noColor}" # store homedirectory -homedirectory=`pwd` +homeDirectory=$(pwd) # ask for permission to proceed -PrintToTerminal "info" "i will download start, stop, restart, backup and many more scripts from github" -read -p "proceed? (y/n): " +Print "info" "i will download start, stop, restart, backup and many more scripts from github" +read -p "prompt: proceed? (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "please press y or n: " REPLY + read -p "prompt: please press y or n: " REPLY done -if [[ $REPLY =~ ^[Yy]$ ]] - then PrintToTerminal "ok" "starting setup..." - else PrintToTerminal "error" "exiting..." - exit 1 +if [[ $REPLY =~ ^[Yy]$ ]]; then + Print "ok" "starting setup..." +else + Print "error" "exiting..." + exit 1 fi # set up server directory -PrintToTerminal "info" "setting up a serverdirectory..." -mkdir "${servername}" -cd "${servername}" - -# 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 - PrintToTerminal "fatal" "unable to connect to github api. script will exit! (maybe chose another branch?)" - exit 1 - else - 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 -PrintToTerminal "info" "downloading scripts from github..." +Print "info" "downloading scripts from github..." # downloading scripts from github # declare all scripts in an array -declare -a scriptsdownload=( "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" "worker.sh" "vent.sh" ) +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") # get length of script array -arraylength=${#scriptsdownload[@]} +arrayLength=${#scriptsDownload[@]} # loop through all entries in the array -for (( i = 0; i < ${arraylength}; i ++ )); do - FetchScriptFromGitHub "${scriptsdownload[${i}]}" +for ((i = 0; i < ${arrayLength}; i++)); do + wget -q -O "${1}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${scriptsDownload[${i}]}" done # user info about download -PrintToTerminal "ok" "download successful" +Print "ok" "download successful" # make selected scripts executable # declare all scripts in an array -declare -a scriptsexecutable=( "start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "maintenance.sh" "prerender.sh" "worker.sh" "vent.sh" ) +declare -a scriptsExecutable=("start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "worker.sh" "vent.sh") # get length of script array -arraylength=${#scriptsexecutable[@]} +arrayLength=${#scriptsExecutable[@]} # loop through all entries in the array -for (( i = 0; i < ${arraylength}; i ++ )); do - chmod +x "${scriptsexecutable[${i}]}" +for ((i = 0; i < ${arrayLength}; i++)); do + chmod +x "${scriptsExecutable[${i}]}" done # store serverdirectory -serverdirectory=`pwd` - -# function for downloading serverfile from mojang api with error checking -function FetchServerFileFromMojang { - PrintToTerminal "info" "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" - PrintToTerminal "ok" "download successful" - if ! [[ -s "minecraft-server.${version}.jar" ]]; then - PrintToTerminal "fatal" "downloaded server-file minecraft-server.${version}.jar is empty or not available" - fi -} +serverDirectory=$(pwd) -# download java executable from mojang.com +# download java executable from mojang PS3="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.18.1") - FetchServerFileFromMojang "125e5adf40c659fd3bce3e66e67a16bb49ecc1b9" - break + "1.18.1") + FetchServerFile "125e5adf40c659fd3bce3e66e67a16bb49ecc1b9" + break ;; - "1.17.1") - FetchServerFileFromMojang "a16d67e5807f57fc4e550299cf20226194497dc2" - break + "1.17.1") + FetchServerFile "a16d67e5807f57fc4e550299cf20226194497dc2" + break ;; - "1.16.5") - FetchServerFileFromMojang "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" - break + "1.16.5") + FetchServerFile "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" + 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 -PrintToTerminal "info" "your server will execute ${serverfile} at start" +Print "info" "your server will execute ${executableServerFile} at start" # set up backupdirectory with child directories -PrintToTerminal "info" "setting up a backupdirectory..." +Print "info" "setting up a backupDirectory..." mkdir world mkdir backups cd backups # declare all backup children in an array -declare -a backupchildren=( "hourly" "daily" "weekly" "monthly" "cached" ) +declare -a backupChildren=("hourly" "daily" "weekly" "monthly" "cached") # get length of backup children array -arraylength=${#backupchildren[@]} -for (( i = 0; i < ${arraylength}; i ++ )); do - mkdir "${backupchildren[${i}]}" +arrayLength=${#backupChildren[@]} +for ((i = 0; i < ${arrayLength}; i++)); do + mkdir "${backupChildren[${i}]}" done -backupdirectory=`pwd` -cd ${serverdirectory} - -# 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 ;^)" +backupDirectory=$(pwd) +cd ${serverDirectory} # eula question -PrintToTerminal "info" "would you like to accept the end user license agreement from mojang?" -PrintToTerminal "info" "if you say no your server will not be able to run" -PrintToTerminal "info" "if you say yes you must abide by their terms and conditions!" -read -p "(y/n): " +Print "info" "would you like to accept the end user license agreement from mojang?" +Print "info" "if you say no your server will not be able to run" +Print "info" "if you say yes you must abide by their terms and conditions!" +read -p "prompt: (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "please press y or n: " REPLY + read -p "prompt: please press y or n: " REPLY done -if [[ ${REPLY} =~ ^[Yy]$ ]] - then PrintToTerminal "ok" "accepting eula..." - echo "eula=true" >> eula.txt - else PrintToTerminal "error" "declining eula..." - echo "eula=false" >> eula.txt +if [[ ${REPLY} =~ ^[Yy]$ ]]; then + Print "ok" "accepting eula..." + echo "eula=true" >>eula.txt +else + Print "error" "declining eula..." + 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 -PrintToTerminal "info" "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}" -StoreToSettings "replacebranch" "${branch}" +Print "info" "storing variables in server.settings..." +StoreSettings "replacePublic" "1.1.1.1" +StoreSettings "replacePrivate" "192.168.1.1" +StoreSettings "replaceMemory" "-Xms2048M" +StoreSettings "replaceThreads" "-XX:ParallelGCThreads=4" +StoreSettings "replaceChangeToConsole" "false" +StoreSettings "replaceEnableWelcomeMessage" "true" +StoreSettings "replaceEnableBackupsWatchdog" "true" +StoreSettings "replaceBranch" "${branch}" +StoreSettings "replaceServerName" "${serverName}" +StoreSettings "replaceHomeDirectory" "${homeDirectory}" +StoreSettings "replaceServerDirectory" "${serverDirectory}" +StoreSettings "replaceBackupDirectory" "${backupDirectory}" +StoreSettings "replaceExecutableServerFile" "${executableServerFile}" # store all the userinput -PrintToTerminal "info" "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}" - -# store to crontab function -function StoreToCrontab { - crontab -l | { cat; echo "${1}"; } | crontab - -} - -# user info -PrintToTerminal "info" "storing config to crontab..." - -# write servername and date into crontab +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 "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") -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 "" +StoreCrontab "# minecraft ${serverName} server automatisation - executed setup.sh at ${date}" +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 messages -PrintToTerminal "ok" "setup is complete!" -PrintToTerminal "info" "if you would like to start your server" -PrintToTerminal "info" "go into your ${green}${serverdirectory}${nocolor} directory" -PrintToTerminal "info" "and execute ${green}./start.sh${nocolor}" -PrintToTerminal "info" "god luck and have fun! ;^)" +Print "ok" "setup is complete!" +Print "info" "if you would like to start your server" +Print "info" "go into your ${green}${serverDirectory}${noColor} directory" +Print "info" "and execute ${green}./start.sh${noColor}" +Print "info" "god luck and have fun! ;^)" # ask user for removal of setup script -read -p "would you like to remove the setup script? (y/n): " +read -p "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 "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 "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 "prompt: please press y or n: " REPLY done if [[ ${REPLY} =~ ^[Yy]$ ]]; then - PrintToTerminal "action" "starting up server..." + Print "action" "starting up server..." ./start.sh --verbose else - PrintToTerminal "ok" "script has finished!" + Print "ok" "script has finished!" fi # exit with code 0 From 1b4dbcd64681aacea0a34ddf9ae1f6addc13eb35 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:16:17 +0100 Subject: [PATCH 049/115] fix: some fiexes --- server.settings | 2 +- setup.sh | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/server.settings b/server.settings index ea50ebc..6456b28 100644 --- a/server.settings +++ b/server.settings @@ -18,8 +18,8 @@ backupDirectory="replaceBackupDirectory" executableServerFile="replaceExecutableServerFile" # script date and time logging -date=$(date +"%Y-%m-%d %H:%M:%S") time=$(date +"%H:%M:%S") +date=$(date +"%Y-%m-%d %H:%M:%S") # memory and threads for java server memory="replaceMemory" diff --git a/setup.sh b/setup.sh index d529164..b73432c 100644 --- a/setup.sh +++ b/setup.sh @@ -21,6 +21,10 @@ cyan="$(tput setaf 6)" white="$(tput setaf 7)" noColor="$(tput sgr0)" +# script date and time logging +time=$(date +"%H:%M:%S") +date=$(date +"%Y-%m-%d %H:%M:%S") + # prints all input to terminal at given log level function Print { if [[ ${1} == "ok" ]]; then From 6120ac385355e3c2c0fe3b1317e2fc98e5e9926d Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:23:59 +0100 Subject: [PATCH 050/115] fix: some setup fixes --- setup.sh | 51 +++++++++++++++++++++------------------------------ 1 file changed, 21 insertions(+), 30 deletions(-) diff --git a/setup.sh b/setup.sh index b73432c..bf462a4 100644 --- a/setup.sh +++ b/setup.sh @@ -10,6 +10,10 @@ TERM="xterm" # branch selection from for github branch="dev" +# script date and time logging +time=$(date +"%H:%M:%S") +date=$(date +"%Y-%m-%d %H:%M:%S") + # command line colours black="$(tput setaf 0)" red="$(tput setaf 1)" @@ -21,10 +25,6 @@ cyan="$(tput setaf 6)" white="$(tput setaf 7)" noColor="$(tput sgr0)" -# script date and time logging -time=$(date +"%H:%M:%S") -date=$(date +"%Y-%m-%d %H:%M:%S") - # prints all input to terminal at given log level function Print { if [[ ${1} == "ok" ]]; then @@ -157,17 +157,17 @@ CheckUnsupported Print "action" "i will setup a minecraft server for you ;^)" # initial question -read -re -i "minecraft" -p "prompt: how should I call your server? your name: " serverName +read -re -i "minecraft" -p "${time} 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 "prompt: please enter a serverName which only contains letters and numbers: " serverName + read -p "${time} prompt: please enter a serverName which only contains letters and numbers: " serverName else regexCheck=true fi if [ -d "${serverName}" ]; then - read -p "prompt: directory ${serverName} already exists - please enter another directory: " serverName + read -p "${time} prompt: directory ${serverName} already exists - please enter another directory: " serverName else existsCheck=true fi @@ -184,10 +184,10 @@ homeDirectory=$(pwd) # ask for permission to proceed Print "info" "i will download start, stop, restart, backup and many more scripts from github" -read -p "prompt: proceed? (y/n): " +read -p "${time} prompt: proceed? (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "prompt: please press y or n: " REPLY + read -p "${time} prompt: please press y or n: " REPLY done if [[ $REPLY =~ ^[Yy]$ ]]; then Print "ok" "starting setup..." @@ -211,7 +211,7 @@ declare -a scriptsDownload=("server.settings" "server.properties" "server.functi arrayLength=${#scriptsDownload[@]} # loop through all entries in the array for ((i = 0; i < ${arrayLength}; i++)); do - wget -q -O "${1}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${scriptsDownload[${i}]}" + wget -q -O "${scriptsDownload[${i}]}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${scriptsDownload[${i}]}" done # user info about download @@ -236,16 +236,13 @@ versions=("1.18.1" "1.17.1" "1.16.5") select version in "${versions[@]}"; do case ${version} in "1.18.1") - FetchServerFile "125e5adf40c659fd3bce3e66e67a16bb49ecc1b9" - break + FetchServerFile "125e5adf40c659fd3bce3e66e67a16bb49ecc1b9" break ;; "1.17.1") - FetchServerFile "a16d67e5807f57fc4e550299cf20226194497dc2" - break + FetchServerFile "a16d67e5807f57fc4e550299cf20226194497dc2" break ;; "1.16.5") - FetchServerFile "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" - break + FetchServerFile "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" break ;; *) echo "please choose an option from the list: " ;; esac @@ -255,7 +252,7 @@ done Print "info" "your server will execute ${executableServerFile} at start" # set up backupdirectory with child directories -Print "info" "setting up a backupDirectory..." +Print "info" "setting up a backupdirectory..." mkdir world mkdir backups cd backups @@ -271,12 +268,10 @@ cd ${serverDirectory} # eula question Print "info" "would you like to accept the end user license agreement from mojang?" -Print "info" "if you say no your server will not be able to run" -Print "info" "if you say yes you must abide by their terms and conditions!" -read -p "prompt: (y/n): " +read -p "${time} prompt: (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "prompt: please press y or n: " REPLY + read -p "${time} prompt: please press y or n: " REPLY done if [[ ${REPLY} =~ ^[Yy]$ ]]; then Print "ok" "accepting eula..." @@ -334,18 +329,14 @@ StoreCrontab "@reboot cd ${serverDirectory} && ./start.sh --quiet" StoreCrontab "" StoreCrontab "" -# finish messages +# finish message Print "ok" "setup is complete!" -Print "info" "if you would like to start your server" -Print "info" "go into your ${green}${serverDirectory}${noColor} directory" -Print "info" "and execute ${green}./start.sh${noColor}" -Print "info" "god luck and have fun! ;^)" # ask user for removal of setup script -read -p "prompt: would you like to remove the setup script? (y/n): " +read -p "${time} prompt: would you like to remove the setup script? (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "prompt: please press y or n: " REPLY + read -p "${time} prompt: please press y or n: " REPLY done if [[ ${REPLY} =~ ^[Yy]$ ]]; then cd "${homeDirectory}" @@ -354,10 +345,10 @@ if [[ ${REPLY} =~ ^[Yy]$ ]]; then fi # ask user to start server now -read -p "prompt: would you like to start your server now? (y/n): " +read -p "${time} prompt: would you like to start your server now? (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "prompt: please press y or n: " REPLY + read -p "${time} prompt: please press y or n: " REPLY done if [[ ${REPLY} =~ ^[Yy]$ ]]; then Print "action" "starting up server..." From a94e9bfdb90c6e7956d7c54eb055e1cb2dd65ce2 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:29:29 +0100 Subject: [PATCH 051/115] fix: more fixes --- setup.sh | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/setup.sh b/setup.sh index bf462a4..47a2eeb 100644 --- a/setup.sh +++ b/setup.sh @@ -135,19 +135,36 @@ 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" - Print "ok" "download successful" - if ! [[ -s "minecraft-server.${version}.jar" ]]; then + 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 -if [ $(id -u) = 0 ]; then - Print "fatal" "please do not run me as root :( - this is dangerous!" - exit 1 -fi +function RootSafety { + if [ $(id -u) = 0 ]; then + Print "fatal" "please do not run me as root :( - this is dangerous!" + exit 1 + fi +} + +# 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 -# run all checks +# os detection CheckLinux CheckMacOS CheckWindows @@ -162,7 +179,7 @@ regex="^[a-zA-Z0-9]+$" verify="false" while [[ ${verify} == false ]]; do if [[ ! "${serverName}" =~ ${regex} ]]; then - read -p "${time} prompt: please enter a serverName which only contains letters and numbers: " serverName + read -p "${time} prompt: please enter a name which only contains letters and numbers: " serverName else regexCheck=true fi From ac251dff5f4b64fdc5fa8b135b2e600b67d5683d Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:33:49 +0100 Subject: [PATCH 052/115] fix: date and time fixes --- server.functions | 26 +++++++++++++------------- server.settings | 4 ---- setup.sh | 16 ++++++---------- 3 files changed, 19 insertions(+), 27 deletions(-) diff --git a/server.functions b/server.functions index 9e3b826..43bbef1 100644 --- a/server.functions +++ b/server.functions @@ -10,51 +10,51 @@ # prints all input to log at given log level function Log { if [[ $1 == "ok" ]]; then - echo "${date} ok: ${2}" >>"${3}" + echo "$(date +"%Y-%m-%d %H:%M:%S") ok: ${2}" >>"${3}" fi if [[ $1 == "info" ]]; then - echo "${date} info: ${2}" >>"${3}" + echo "$(date +"%Y-%m-%d %H:%M:%S") info: ${2}" >>"${3}" fi if [[ $1 == "warn" ]]; then - echo "${date} warn: ${2}" >>"${3}" + echo "$(date +"%Y-%m-%d %H:%M:%S") warn: ${2}" >>"${3}" fi if [[ $1 == "error" ]]; then - echo "${date} error: ${2}" >>"${3}" + echo "$(date +"%Y-%m-%d %H:%M:%S") error: ${2}" >>"${3}" fi if [[ $1 == "fatal" ]]; then - echo "${date} fatal: ${2}" >>"${3}" + echo "$(date +"%Y-%m-%d %H:%M:%S") fatal: ${2}" >>"${3}" fi if [[ $1 == "action" ]]; then - echo "${date} action: ${2}" >>"${3}" + 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 "${time} ${green}ok${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${green}ok${noColor}: ${2}" fi if [[ ${1} == "info" ]] && [[ ${verbose} == true ]] && [[ ${quiet} == false ]]; then - echo "${time} ${blue}info${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${blue}info${noColor}: ${2}" fi if [[ ${1} == "warn" ]]; then - echo "${time} ${yellow}warn${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${yellow}warn${noColor}: ${2}" fi if [[ ${1} == "error" ]]; then - echo "${time} ${red}error${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${red}error${noColor}: ${2}" fi if [[ ${1} == "fatal" ]]; then - echo "${time} ${red}fatal${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${red}fatal${noColor}: ${2}" fi if [[ ${1} == "action" ]] && [[ ${quiet} == false ]]; then - echo "${time} ${cyan}action${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${cyan}action${noColor}: ${2}" fi } # checks if debug mode is on function Debug { if [[ ${enableDebug} == true ]]; then - echo "${date} ${1}" >>"${debugLog}" + echo "$(date +"%Y-%m-%d %H:%M:%S") ${1}" >>"${debugLog}" fi } diff --git a/server.settings b/server.settings index 6456b28..71e0457 100644 --- a/server.settings +++ b/server.settings @@ -17,10 +17,6 @@ serverDirectory="replaceServerDirectory" backupDirectory="replaceBackupDirectory" executableServerFile="replaceExecutableServerFile" -# script date and time logging -time=$(date +"%H:%M:%S") -date=$(date +"%Y-%m-%d %H:%M:%S") - # memory and threads for java server memory="replaceMemory" threads="replaceThreads" diff --git a/setup.sh b/setup.sh index 47a2eeb..cc2d01b 100644 --- a/setup.sh +++ b/setup.sh @@ -10,10 +10,6 @@ TERM="xterm" # branch selection from for github branch="dev" -# script date and time logging -time=$(date +"%H:%M:%S") -date=$(date +"%Y-%m-%d %H:%M:%S") - # command line colours black="$(tput setaf 0)" red="$(tput setaf 1)" @@ -28,22 +24,22 @@ noColor="$(tput sgr0)" # prints all input to terminal at given log level function Print { if [[ ${1} == "ok" ]]; then - echo "${time} ${green}ok${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${green}ok${noColor}: ${2}" fi if [[ ${1} == "info" ]]; then - echo "${time} ${blue}info${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${blue}info${noColor}: ${2}" fi if [[ ${1} == "warn" ]]; then - echo "${time} ${yellow}warn${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${yellow}warn${noColor}: ${2}" fi if [[ ${1} == "error" ]]; then - echo "${time} ${red}error${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${red}error${noColor}: ${2}" fi if [[ ${1} == "fatal" ]]; then - echo "${time} ${red}fatal${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${red}fatal${noColor}: ${2}" fi if [[ ${1} == "action" ]]; then - echo "${time} ${cyan}action${noColor}: ${2}" + echo "$(date +"%H:%M:%S") ${cyan}action${noColor}: ${2}" fi } From 4259890bbce154a4fe4d9a81d55eb8ca850fc473 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:35:33 +0100 Subject: [PATCH 053/115] chore: commenting changes --- setup.sh | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/setup.sh b/setup.sh index cc2d01b..ac25c7f 100644 --- a/setup.sh +++ b/setup.sh @@ -190,6 +190,8 @@ while [[ ${verify} == false ]]; do verify=false fi done + +# user info Print "info" "your server will be called ${green}${serverName}${noColor}" # store homedirectory @@ -218,11 +220,8 @@ cd "${serverName}" Print "info" "downloading scripts from github..." # downloading scripts from github -# declare all scripts in an array 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") -# get length of script array arrayLength=${#scriptsDownload[@]} -# loop through all entries in the array for ((i = 0; i < ${arrayLength}; i++)); do wget -q -O "${scriptsDownload[${i}]}" "https://raw.githubusercontent.com/Simylein/MinecraftServer/${branch}/${scriptsDownload[${i}]}" done @@ -231,11 +230,8 @@ done Print "ok" "download successful" # make selected scripts executable -# declare all scripts in an array declare -a scriptsExecutable=("start.sh" "restore.sh" "reset.sh" "restart.sh" "stop.sh" "backup.sh" "update.sh" "worker.sh" "vent.sh") -# get length of script array arrayLength=${#scriptsExecutable[@]} -# loop through all entries in the array for ((i = 0; i < ${arrayLength}; i++)); do chmod +x "${scriptsExecutable[${i}]}" done @@ -269,9 +265,7 @@ Print "info" "setting up a backupdirectory..." mkdir world mkdir backups cd backups -# declare all backup children in an array declare -a backupChildren=("hourly" "daily" "weekly" "monthly" "cached") -# get length of backup children array arrayLength=${#backupChildren[@]} for ((i = 0; i < ${arrayLength}; i++)); do mkdir "${backupChildren[${i}]}" @@ -294,7 +288,7 @@ else echo "eula=false" >>eula.txt fi -# store all the userinput +# store to settings Print "info" "storing variables in server.settings..." StoreSettings "replacePublic" "1.1.1.1" StoreSettings "replacePrivate" "192.168.1.1" @@ -310,7 +304,7 @@ StoreSettings "replaceServerDirectory" "${serverDirectory}" StoreSettings "replaceBackupDirectory" "${backupDirectory}" StoreSettings "replaceExecutableServerFile" "${executableServerFile}" -# store all the userinput +# store to properties Print "info" "storing variables in server.properties..." StoreProperties "white-list=false" "white-list=true" StoreProperties "enforce-whitelist=false" "enforce-whitelist=true" From 45c42c6583c4b4ad3a362e1e91cd961df6529465 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:36:28 +0100 Subject: [PATCH 054/115] fix: break in server version question --- setup.sh | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/setup.sh b/setup.sh index ac25c7f..ebc946f 100644 --- a/setup.sh +++ b/setup.sh @@ -245,13 +245,16 @@ versions=("1.18.1" "1.17.1" "1.16.5") select version in "${versions[@]}"; do case ${version} in "1.18.1") - FetchServerFile "125e5adf40c659fd3bce3e66e67a16bb49ecc1b9" break + FetchServerFile "125e5adf40c659fd3bce3e66e67a16bb49ecc1b9" + break ;; "1.17.1") - FetchServerFile "a16d67e5807f57fc4e550299cf20226194497dc2" break + FetchServerFile "a16d67e5807f57fc4e550299cf20226194497dc2" + break ;; "1.16.5") - FetchServerFile "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" break + FetchServerFile "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" + break ;; *) echo "please choose an option from the list: " ;; esac From 14fab93d0e0d9e9a5563da8a3d721aebdfbac8a0 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:37:26 +0100 Subject: [PATCH 055/115] fix: more fixes --- setup.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/setup.sh b/setup.sh index ebc946f..49f76e5 100644 --- a/setup.sh +++ b/setup.sh @@ -256,7 +256,9 @@ select version in "${versions[@]}"; do FetchServerFile "1b557e7b033b583cd9f66746b7a9ab1ec1673ced" break ;; - *) echo "please choose an option from the list: " ;; + *) + echo "please choose an option from the list: " + ;; esac done From cd58584fef8da133689c945a674264e8406603f8 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:38:21 +0100 Subject: [PATCH 056/115] fix: variable fix --- server.settings | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.settings b/server.settings index 71e0457..66977f1 100644 --- a/server.settings +++ b/server.settings @@ -5,7 +5,7 @@ # if you know what you are doing, feel free to tinker with them ;^) # your contact info for players -adminContact"your admin did not edit the server settings file /:" +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") From 9d47d4ce4c74571678e8f0952faa1d7ab92d430e Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:40:57 +0100 Subject: [PATCH 057/115] fix: prompt time display fix --- setup.sh | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/setup.sh b/setup.sh index 49f76e5..a7317ef 100644 --- a/setup.sh +++ b/setup.sh @@ -170,17 +170,17 @@ CheckUnsupported Print "action" "i will setup a minecraft server for you ;^)" # initial question -read -re -i "minecraft" -p "${time} prompt: how should I call your server? 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 "${time} prompt: please enter a name which only contains letters and numbers: " serverName + read -p "$(date +"%H:%M:%S") prompt: please enter a name which only contains letters and numbers: " serverName else regexCheck=true fi if [ -d "${serverName}" ]; then - read -p "${time} prompt: directory ${serverName} already exists - please enter another directory: " serverName + read -p "$(date +"%H:%M:%S") prompt: directory ${serverName} already exists - please enter another directory: " serverName else existsCheck=true fi @@ -199,10 +199,10 @@ homeDirectory=$(pwd) # ask for permission to proceed Print "info" "i will download start, stop, restart, backup and many more scripts from github" -read -p "${time} prompt: proceed? (y/n): " +read -p "$(date +"%H:%M:%S") prompt: proceed? (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "${time} prompt: please press y or n: " REPLY + read -p "$(date +"%H:%M:%S") prompt: please press y or n: " REPLY done if [[ $REPLY =~ ^[Yy]$ ]]; then Print "ok" "starting setup..." @@ -280,10 +280,10 @@ cd ${serverDirectory} # eula question Print "info" "would you like to accept the end user license agreement from mojang?" -read -p "${time} prompt: (y/n): " +read -p "$(date +"%H:%M:%S") prompt: (y/n): " regex="^(Y|y|N|n)$" while [[ ! ${REPLY} =~ ${regex} ]]; do - read -p "${time} prompt: please press y or n: " REPLY + read -p "$(date +"%H:%M:%S") prompt: please press y or n: " REPLY done if [[ ${REPLY} =~ ^[Yy]$ ]]; then Print "ok" "accepting eula..." @@ -345,10 +345,10 @@ StoreCrontab "" Print "ok" "setup is complete!" # ask user for removal of setup script -read -p "${time} prompt: 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 "${time} prompt: 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}" @@ -357,10 +357,10 @@ if [[ ${REPLY} =~ ^[Yy]$ ]]; then fi # ask user to start server now -read -p "${time} prompt: 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 "${time} prompt: please press y or n: " REPLY + read -p "$(date +"%H:%M:%S") prompt: please press y or n: " REPLY done if [[ ${REPLY} =~ ^[Yy]$ ]]; then Print "action" "starting up server..." From a54d4ddf437de5ed078cef6ad022b484c719a10f Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:47:34 +0100 Subject: [PATCH 058/115] fix: backup category function --- server.functions | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/server.functions b/server.functions index 43bbef1..ce5e33e 100644 --- a/server.functions +++ b/server.functions @@ -100,16 +100,16 @@ function ParseCategory { isWeekly=false isMonthly=false # test and set backup category - if [[ $1 == "hourly" ]]; then + if [[ $1 == "--hourly" ]]; then isHourly=true shift - elif [[ $1 == "hourly" ]]; then + elif [[ $1 == "--daily" ]]; then isDaily=true shift - elif [[ $1 == "hourly" ]]; then + elif [[ $1 == "--weekly" ]]; then isWeekly=true shift - elif [[ $1 == "hourly" ]]; then + elif [[ $1 == "--monthly" ]]; then isMonthly=true shift else From 4d116f985a84b7e90c2a55840e62a966d2331043 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:48:52 +0100 Subject: [PATCH 059/115] fix: parse arguments --- server.functions | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/server.functions b/server.functions index ce5e33e..d029412 100644 --- a/server.functions +++ b/server.functions @@ -74,16 +74,36 @@ function ParseArgs { verbose=false while [[ $# -gt 0 ]]; do case "${1}" in - -f) force=true ;; - -h) help=true ;; - -n) now=true ;; - -q) quiet=true ;; - -v) verbose=true ;; - --force) force=true ;; - --help) help=true ;; - --now) now=true ;; - --quiet) quiet=true ;; - --verbose) verbose=true ;; + -f) + force=true + ;; + -h) + help=true + ;; + -n) + now=true + ;; + -q) + quiet=true + ;; + -v) + verbose=true + ;; + --force) + force=true + ;; + --help) + help=true + ;; + --now) + now=true + ;; + --quiet) + quiet=true + ;; + --verbose) + verbose=true + ;; *) Print "warn" "bad argument: ${1}" Print "info" "for help use --help" From 9f5c71443ec7327fc97add97f6932c30fec424a1 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:56:26 +0100 Subject: [PATCH 060/115] fix: backup args parsing --- backup.sh | 3 +++ server.functions | 5 ----- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/backup.sh b/backup.sh index df5b6a7..6ba9fb3 100644 --- a/backup.sh +++ b/backup.sh @@ -16,6 +16,9 @@ ScriptSafety # parse backup category ParseCategory "$@" +# shift args +shift + # parse arguments ParseArgs "$@" diff --git a/server.functions b/server.functions index d029412..7f55f0a 100644 --- a/server.functions +++ b/server.functions @@ -122,19 +122,14 @@ function ParseCategory { # test and set backup category if [[ $1 == "--hourly" ]]; then isHourly=true - shift elif [[ $1 == "--daily" ]]; then isDaily=true - shift elif [[ $1 == "--weekly" ]]; then isWeekly=true - shift elif [[ $1 == "--monthly" ]]; then isMonthly=true - shift else Print "error" "$1 is not a backup category" - shift fi } From 2920a5de3b63ff493dd9a366e7501813022292df Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 18:57:56 +0100 Subject: [PATCH 061/115] fix: server version prompt --- setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.sh b/setup.sh index a7317ef..3f6f6d2 100644 --- a/setup.sh +++ b/setup.sh @@ -240,7 +240,7 @@ done serverDirectory=$(pwd) # download java executable from mojang -PS3="which server version would you like to install? " +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 From 49761aca4ba3f3527a7312cd181021bb0c944712 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 19:02:10 +0100 Subject: [PATCH 062/115] fix: counter increment --- worker.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/worker.sh b/worker.sh index e3daf85..2d6cee7 100644 --- a/worker.sh +++ b/worker.sh @@ -81,6 +81,6 @@ while true; do fi lastLineBuffer="${lineBuffer}" - counter++ + counter$((counter + 1)) sleep 1s done From d549eae4f308ba9bc59b94ff1ecc5bd3dd4b013a Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 19:07:23 +0100 Subject: [PATCH 063/115] fix: variable name server file --- server.functions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.functions b/server.functions index 7f55f0a..a6c3ac1 100644 --- a/server.functions +++ b/server.functions @@ -194,7 +194,7 @@ function LookForScreen { # check for executable function CheckExecutable { - if ! ls ${serverfile}* 1>/dev/null 2>&1; then + if ! ls ${executableServerFile}* 1>/dev/null 2>&1; then Log "fatal" "no executable found" >>"${screenLog}" Print "fatal" "no executable found" exit 1 From 3411e393358bc50dfd515aed43f2c58fc6b27cda Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 19:09:14 +0100 Subject: [PATCH 064/115] feat: added helpful error message --- server.functions | 1 + 1 file changed, 1 insertion(+) diff --git a/server.functions b/server.functions index a6c3ac1..27c5ae0 100644 --- a/server.functions +++ b/server.functions @@ -130,6 +130,7 @@ function ParseCategory { isMonthly=true else Print "error" "$1 is not a backup category" + Print "info" "use --hourly, --daily, --weekly, --monthly" fi } From 25499393e97e6c27d31375ebd93c975abe03611d Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 19:12:39 +0100 Subject: [PATCH 065/115] feat: startup checks now smarter --- start.sh | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/start.sh b/start.sh index 3c05eeb..18963c4 100644 --- a/start.sh +++ b/start.sh @@ -58,9 +58,9 @@ count="0" counter="0" startupChecks="0" while [ ${startupChecks} -lt 120 ]; do - if tail "${screenLog}" | grep -q "Thread Query Listener started"; then - Log "ok" "server startup successful - query up and running" "${screenLog}" - Print "ok" "server startup successful - query up and running" + 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 @@ -115,8 +115,10 @@ done # check if screenlog does not contain startup confirmation if ! tail "${screenLog}" | grep -q "Thread Query Listener started"; then - Log "warn" "server startup unsuccessful - perhaps query is disabled" "${screenLog}" - Print "warn" "server startup unsuccessful - perhaps query is disabled" + Log "warn" "server startup unsuccessful" "${screenLog}" + Print "warn" "server startup unsuccessful" + Print "info" "crash dump - last 10 lines of ${screenLog}" + tail -10 "${screenLog}" fi # enable worker script From 6f3f1176cc85d1cf3de927824948d13451317c48 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 19:17:08 +0100 Subject: [PATCH 066/115] fix: venting prompt --- vent.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vent.sh b/vent.sh index e473b6b..f6ad2e3 100644 --- a/vent.sh +++ b/vent.sh @@ -28,11 +28,11 @@ CheckScreen # user safety function for confirmation Print "warn" "are you sure you want to vent your server?" -read -p "if so, please type ${red}confirm venting${noColor} " +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 - Print "error" "wrong token - please try again" + Print "error" "wrong venting token - you may try again" exit 1 fi From 23ed9c59890fb3ced23fec3027710b4a6d1fbc1c Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 19:20:56 +0100 Subject: [PATCH 067/115] fix: counter fix --- worker.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/worker.sh b/worker.sh index 2d6cee7..fc6d187 100644 --- a/worker.sh +++ b/worker.sh @@ -81,6 +81,6 @@ while true; do fi lastLineBuffer="${lineBuffer}" - counter$((counter + 1)) + counter=$((counter + 1)) sleep 1s done From 7596e1a839bd8c34a25cb75c73b57810a5a708e9 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 19:23:16 +0100 Subject: [PATCH 068/115] fix: start checks --- start.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/start.sh b/start.sh index 18963c4..b0d16c1 100644 --- a/start.sh +++ b/start.sh @@ -114,7 +114,7 @@ while [ ${startupChecks} -lt 120 ]; do done # check if screenlog does not contain startup confirmation -if ! tail "${screenLog}" | grep -q "Thread Query Listener started"; then +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}" From 9c9a324a18f1b17d958b72c9ed4f6b0512cbb44a Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 19:27:46 +0100 Subject: [PATCH 069/115] fix: log choices --- vent.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vent.sh b/vent.sh index f6ad2e3..0038aa1 100644 --- a/vent.sh +++ b/vent.sh @@ -55,7 +55,7 @@ cd "${homeDirectory}" # remove crontab crontab -r # remove serverdirectory -Print "info" "deleting server..." +Print "action" "deleting server..." rm -r "${serverName}" # check if vent was successful if ! [ -d "${serverDirectory}" ]; then From d6eb47f86d8ae9a1240a82f860489d10c8d075e3 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 19:30:53 +0100 Subject: [PATCH 070/115] fix: crontab date execute fix --- setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.sh b/setup.sh index 3f6f6d2..e13a3a4 100644 --- a/setup.sh +++ b/setup.sh @@ -323,7 +323,7 @@ StoreProperties "motd=A Minecraft Server" "motd=Hello World, I am your new Minec # 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}" +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" From d0b3672790f6bedcabf091c360ed1cae6e36fa79 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 19:38:14 +0100 Subject: [PATCH 071/115] fix: added space for better format --- server.functions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.functions b/server.functions index 27c5ae0..0ca266f 100644 --- a/server.functions +++ b/server.functions @@ -225,7 +225,7 @@ 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}\"}]" + Screen "tellraw ${1} [\"\",{\"text\":\"[Script] \",\"color\":\"blue\"},{\"text\":\"${2} \"},{\"text\":\"${3}\",\"color\":\"${4}\"}]" fi } From 8afc40d4a8434d9e45940513ac17d647a9d6475d Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 20:15:42 +0100 Subject: [PATCH 072/115] fix: infinity loop --- server.functions | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/server.functions b/server.functions index 0ca266f..657f51c 100644 --- a/server.functions +++ b/server.functions @@ -510,10 +510,11 @@ 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: admin contact info: ${adminContact}" TellrawPlayer "${player}" "info: available commands: (seperated by comma)" TellrawPlayer "${player}" "info: list tasks, list backups" - TellrawPlayer "${player}" "info: perform backup, perform restart, perform update, perform reset" + TellrawPlayer "${player}" "info: perform backup, perform restart" + TellrawPlayer "${player}" "info: perform update, perform reset" + TellrawPlayer "${player}" "info: admin contact info: ${adminContact}" # spam protection sleep 10s fi From 981eaac46461173822b76cccd7dda8b0d0e262e2 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 20:17:14 +0100 Subject: [PATCH 073/115] fix: more infinity loops --- server.functions | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server.functions b/server.functions index 657f51c..5d6ac00 100644 --- a/server.functions +++ b/server.functions @@ -556,6 +556,7 @@ function ListTasks { else TellrawPlayer "${player}" "perform reset is" "undefined" "grey" fi + TellrawPlayer "${player}" "config is located in file server.settings" # spam protection sleep 20s else @@ -601,6 +602,7 @@ function ListBackups { else TellrawPlayer "${player}" "monthly backup is" "undefined" "grey" fi + TellrawPlayer "${player}" "config is located in file server.settings" # spam protection sleep 20s else From 81af3c55157dce1443a840516d55a6ef593f0e0c Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 20:41:35 +0100 Subject: [PATCH 074/115] feat: restore script should work now --- restore.sh | 219 ++++++++++++++++++++++------------------------------- 1 file changed, 90 insertions(+), 129 deletions(-) diff --git a/restore.sh b/restore.sh index 2c20538..7114d28 100644 --- a/restore.sh +++ b/restore.sh @@ -1,199 +1,160 @@ #!/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 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 +# safety checks +RootSafety +ScriptSafety -# 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 "$@" -# 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 restore script" - -# parsing script arguments -ParseScriptArguments "$@" +# check for existance of executable +CheckExecutable -# check for script lock -CheckScriptLock - -# write date to logfile -echo "action: ${date} executing restore 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 +# look if server is running +CheckScreen # prints countdown to screen -PerformCountdown "restoring a backup" +Countdown "restoring a backup" # server stop -PerformServerStop +Stop # awaits server stop -AwaitServerStop +AwaitStop # force quit server if not stopped -ConditionalForceQuit +ForceQuit # output confirmed stop -PrintToLog "ok" "server successfully stopped!" "${screenlog}" -CheckQuiet "ok" "server successfully stopped!" +Log "ok" "server successfully stopped" "${screenLog}" +Print "ok" "server successfully stopped" # create backup -CreateCachedBackup "restore" +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}" +Print "info" "selected backup to restore: ${backupDirectory}/${cachedDailyHourlyWeeklyMonthly}/${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 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} - PrintToTerminal "warn" "canceling backup restore..." - PrintToTerminal "action" "restarting server..." - PrintToLog "info" "backup restore has been canceled" "${screenlog}" - PrintToLog "info" "resuming to current live world" "${screenlog}" +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 "$@" fi # log to debug if true -CheckDebug "executed restore script" +Debug "executed $0 script" # exit with code 0 exit 0 From d72a05694747f2909bf2dda190fce42d89ae94f1 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 20:41:50 +0100 Subject: [PATCH 075/115] feat: make info log level visible by default --- server.functions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.functions b/server.functions index 5d6ac00..887dd69 100644 --- a/server.functions +++ b/server.functions @@ -34,7 +34,7 @@ function Print { if [[ ${1} == "ok" ]] && [[ ${quiet} == false ]]; then echo "$(date +"%H:%M:%S") ${green}ok${noColor}: ${2}" fi - if [[ ${1} == "info" ]] && [[ ${verbose} == true ]] && [[ ${quiet} == false ]]; then + if [[ ${1} == "info" ]] && [[ ${quiet} == false ]]; then echo "$(date +"%H:%M:%S") ${blue}info${noColor}: ${2}" fi if [[ ${1} == "warn" ]]; then From 13a61846c9f1e123dcf05ad4f8da7340b25643fd Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 20:54:29 +0100 Subject: [PATCH 076/115] fix: restore script is working now --- restore.sh | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/restore.sh b/restore.sh index 7114d28..8219d10 100644 --- a/restore.sh +++ b/restore.sh @@ -108,9 +108,6 @@ elif [[ "${cachedDailyHourlyWeeklyMonthly}" == "${backups[4]}" ]]; then done fi -# echo selected backup -Print "info" "selected backup to restore: ${backupDirectory}/${cachedDailyHourlyWeeklyMonthly}/${backup}" - # ask for permission to proceed 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" @@ -125,12 +122,13 @@ if [[ ${REPLY} =~ ^[Yy]$ ]]; then 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 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 - Log "the backup ${backupdirectory}/${cachedDailyHourlyWeeklyMonthly}/${backup} has been restored" "${screenLog}" + 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" From 9d8e819e7bead390c9969060329f03993ef81d51 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 30 Dec 2021 21:04:53 +0100 Subject: [PATCH 077/115] feat: new improved update script --- update.sh | 150 ++++++++++++++++++++++-------------------------------- 1 file changed, 61 insertions(+), 89 deletions(-) diff --git a/update.sh b/update.sh index 227e06f..64c218c 100644 --- a/update.sh +++ b/update.sh @@ -1,127 +1,99 @@ #!/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 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 +# safety checks +RootSafety +ScriptSafety -# 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 "$@" -# 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 update script" - -# parsing script arguments -ParseScriptArguments "$@" - -# check for script lock -CheckScriptLock - -# write date to logfile -PrintToLog "action" "${date} executing update script" "${screenlog}" - -# check if server is running -if screen -list | grep -q "\.${servername}"; then - - # prints countdown to screen - PerformCountdown "updating" - - # server stop - PerformServerStop - - # awaits server stop - AwaitServerStop - - # force quit server if not stopped - ConditionalForceQuit - - # output confirmed stop - PrintToLog "ok" "server successfully stopped!" "${screenlog}" - CheckQuiet "ok" "server successfully stopped!" -fi +# check for existance of executable +CheckExecutable + +# look if server is running +CheckScreen + +# prints countdown to screen +Countdown "stopping" + +# server stop +Stop + +# awaits server stop +AwaitStop + +# force quit server if not stopped +ForceQuit + +# output confirmed stop +Log "ok" "server successfully stopped" "${screenLog}" +Print "ok" "server successfully stopped" # create backup -CreateCachedBackup "update" +CachedBackup "update" + +# 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/125e5adf40c659fd3bce3e66e67a16bb49ecc1b9/server.jar" +wget --spider --quiet "${url}" if [ "$?" != 0 ]; then - PrintToTerminal "warn" "unable to connect to mojang api skipping update..." - PrintToLog "warn" "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 "ok" "downloading newest server version..." - PrintToLog "info" "downloading newest server version..." "${screenlog}" + Log "info" "downloading newest server version..." "${screenLog}" + Print "ok" "downloading newest server version..." # check if already on newest version - if [[ "${serverfile}" = *"minecraft-server.1.18.1.jar" ]]; then - CheckVerbose "info" "you are running the newest server version - skipping update" - PrintToLog "info" "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.18.1.jar" "https://launcher.mojang.com/v1/objects/125e5adf40c659fd3bce3e66e67a16bb49ecc1b9/server.jar" + wget -q -O "minecraft-server.${version}.jar" "${url}" # update serverfile variable in server.settings - newserverfile="${serverdirectory}/minecraft-server.1.18.0.jar" + newExecutableServerFile="${serverDirectory}/minecraft-server.${version}.jar" # if new serverfile exists remove oldserverfile - if [ -f "${newserverfile}" ]; then - CheckVerbose "ok" "updating server.settings for startup with new server version 1.18.1" - sed -i "s|${serverfile}|${newserverfile}|g" "server.settings" + if [ -s "${newExecutableServerFile}" ]; then + Log "ok" "updating server.settings for startup with new server version ${version}" "${screenLog}" + Print "ok" "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 - PrintToTerminal "warn" "could not remove old server-file ${serverfile} because new server-file ${newserverfile} is missing" - CheckQuiet "info" "server will startup with old server-file ${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 "action" "restarting server..." +Print "action" "restarting server..." ./start.sh "$@" # log to debug if true -CheckDebug "executed update script" +Debug "executed $0 script" # exit with code 0 exit 0 From a82369a5aadbe1f2840a07644773a5ae6cc0cc03 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Fri, 31 Dec 2021 12:00:16 +0100 Subject: [PATCH 078/115] feat: verbose now has a use case debug infos --- server.functions | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/server.functions b/server.functions index 887dd69..8a16d13 100644 --- a/server.functions +++ b/server.functions @@ -49,12 +49,18 @@ function Print { if [[ ${1} == "action" ]] && [[ ${quiet} == false ]]; then echo "$(date +"%H:%M:%S") ${cyan}action${noColor}: ${2}" fi + if [[ $1 == "debug" ]] && [[ ${quiet} == false ]] && [[ ${debug} == true ]]; 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}" + if [[ ${verbose} == true ]]; then + Print "debug" "${1}" + fi fi } @@ -339,8 +345,9 @@ scriptsLength=${#scripts[@]} function RemoveScripts { # remove scripts from serverdirectory # loop through all entries in the array + Print "info" "removing scripts..." for ((i = 1; i < ${scriptsLength} + 1; i++)); do - Print "info" "removing script ${scripts[${i} - 1]}" + Print "debug" "removing script ${scripts[${i} - 1]}" rm "${scripts[${i} - 1]}" done } @@ -349,8 +356,9 @@ function RemoveScripts { function DownloadScripts { # downloading scripts from github # loop through all entries in the array + Print "info" "downloading scripts..." for ((i = 0; i < ${scriptsLength}; i++)); do - Print "info" "downloading script ${scripts[${i}]} from branch ${branch} on github..." + Print "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 } @@ -359,8 +367,9 @@ function DownloadScripts { 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 - Print "info" "setting script ${scripts[${i}]} executable" + Print "debug" "setting script ${scripts[${i}]} executable" chmod +x ${scripts[${i}]} done } From 8c04341f360ba39e3a913878deb2867088d2ee3f Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Fri, 31 Dec 2021 12:08:47 +0100 Subject: [PATCH 079/115] fix: minor update fixes --- server.functions | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/server.functions b/server.functions index 8a16d13..8b8f258 100644 --- a/server.functions +++ b/server.functions @@ -346,9 +346,9 @@ function RemoveScripts { # remove scripts from serverdirectory # loop through all entries in the array Print "info" "removing scripts..." - for ((i = 1; i < ${scriptsLength} + 1; i++)); do - Print "debug" "removing script ${scripts[${i} - 1]}" - rm "${scripts[${i} - 1]}" + for ((i = 0; i < ${scriptsLength}; i++)); do + Debug "removing script ${scripts[${i}]}" + rm "${scripts[${i}]}" done } @@ -358,7 +358,7 @@ function DownloadScripts { # loop through all entries in the array Print "info" "downloading scripts..." for ((i = 0; i < ${scriptsLength}; i++)); do - Print "debug" "downloading script ${scripts[${i}]} from branch ${branch} on github..." + 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 } @@ -369,7 +369,7 @@ function ExecutableScripts { # loop through all entries in the array Print "info" "making scripts executable..." for ((i = 0; i < ${scriptsLength}; i++)); do - Print "debug" "setting script ${scripts[${i}]} executable" + Debug "setting script ${scripts[${i}]} executable" chmod +x ${scripts[${i}]} done } From af704494887173b0e2cbff32243e6cc3e3920f11 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Fri, 31 Dec 2021 12:12:18 +0100 Subject: [PATCH 080/115] fix: debug printing --- server.functions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.functions b/server.functions index 8b8f258..aa41b02 100644 --- a/server.functions +++ b/server.functions @@ -49,7 +49,7 @@ function Print { if [[ ${1} == "action" ]] && [[ ${quiet} == false ]]; then echo "$(date +"%H:%M:%S") ${cyan}action${noColor}: ${2}" fi - if [[ $1 == "debug" ]] && [[ ${quiet} == false ]] && [[ ${debug} == true ]]; then + if [[ $1 == "debug" ]] && [[ ${quiet} == false ]]; then echo "$(date +"%H:%M:%S") debug: ${2}" fi } From 192c0fb9385563a8a12785870661eb685f6eed42 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Fri, 31 Dec 2021 12:15:32 +0100 Subject: [PATCH 081/115] fix: venting lets worker script exit --- worker.sh | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/worker.sh b/worker.sh index fc6d187..a9f677e 100644 --- a/worker.sh +++ b/worker.sh @@ -24,6 +24,15 @@ CheckScreen # run various functions every second until server exits counter=0 while true; do + 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 @@ -75,11 +84,6 @@ while true; do fi fi - if ! screen -list | grep -q "\.${serverName}"; then - Debug "executed $0 script" - exit 0 - fi - lastLineBuffer="${lineBuffer}" counter=$((counter + 1)) sleep 1s From f744e76997bddc660d1cf66ef746342836edc200 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Fri, 31 Dec 2021 12:23:13 +0100 Subject: [PATCH 082/115] fix: debug print work even if debug is false --- server.functions | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/server.functions b/server.functions index aa41b02..a18f9de 100644 --- a/server.functions +++ b/server.functions @@ -58,9 +58,9 @@ function Print { function Debug { if [[ ${enableDebug} == true ]]; then echo "$(date +"%Y-%m-%d %H:%M:%S") ${1}" >>"${debugLog}" - if [[ ${verbose} == true ]]; then - Print "debug" "${1}" - fi + fi + if [[ ${verbose} == true ]]; then + Print "debug" "${1}" fi } From ba61ef089103528c76ace09ae489e7c9f1f37eee Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Fri, 31 Dec 2021 12:53:11 +0100 Subject: [PATCH 083/115] fix: spelling actions --- update.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/update.sh b/update.sh index 64c218c..60f1717 100644 --- a/update.sh +++ b/update.sh @@ -25,7 +25,7 @@ CheckExecutable CheckScreen # prints countdown to screen -Countdown "stopping" +Countdown "updating" # server stop Stop From 2d8d4b862fa33ca3d3c3621bd1096a11db76162b Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 1 Jan 2022 01:05:05 +0100 Subject: [PATCH 084/115] fix: nicer numbers --- server.settings | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/server.settings b/server.settings index 66977f1..a3e1230 100644 --- a/server.settings +++ b/server.settings @@ -46,9 +46,9 @@ 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 "-18 days" +"%Y-%m-%d") -oldWeekly=$(date -d "-12 weeks" +"week-%U") -oldMonthly=$(date -d "-6 months" +"%B" | awk '{print tolower($0)}') +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) From 6edabb75aa5bd0bfd804f9c702b7d7f9ca8af738 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 1 Jan 2022 15:43:23 +0100 Subject: [PATCH 085/115] fix: trying to fix scripts lock function --- server.functions | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/server.functions b/server.functions index a18f9de..45bd3d9 100644 --- a/server.functions +++ b/server.functions @@ -168,12 +168,14 @@ function RootSafety { } # checks if a script is already running +# TODO: fix this mess (not working) function ScriptSafety { if [[ ${force} == false ]]; then - declare -a arr=("reset.sh" "restart.sh" "restore.sh" "start.sh" "stop.sh" "update.sh" "vent.sh") - for i in "${scriptslock[@]}"; do - if pidof -x "${scriptslock[i]}" &>/dev/null; then - Print "warn" "script ${scriptslock[i]} is already running" + declare -a scriptsLock=("backup.sh" "reset.sh" "restart.sh" "restore.sh" "start.sh" "stop.sh" "update.sh" "vent.sh") + scriptsLockLength=${#scripts[@]} + for ((i = 0; i < ${scriptsLockLength}; i++)); do + if pgrep --list-full ${scriptsLock[i]} | grep -q ${scriptsLock[i]} &>/dev/null; then + Print "warn" "script ${scriptsLock[i]} is already running" Print "info" "use --force option to ignore this safety check" exit 1 fi @@ -524,8 +526,6 @@ function Help { TellrawPlayer "${player}" "info: perform backup, perform restart" TellrawPlayer "${player}" "info: perform update, perform reset" TellrawPlayer "${player}" "info: admin contact info: ${adminContact}" - # spam protection - sleep 10s fi } @@ -566,8 +566,6 @@ function ListTasks { TellrawPlayer "${player}" "perform reset is" "undefined" "grey" fi TellrawPlayer "${player}" "config is located in file server.settings" - # spam protection - sleep 20s 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" @@ -612,8 +610,6 @@ function ListBackups { TellrawPlayer "${player}" "monthly backup is" "undefined" "grey" fi TellrawPlayer "${player}" "config is located in file server.settings" - # spam protection - sleep 20s 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" @@ -630,8 +626,6 @@ function PerformBackup { TellrawPlayer "${player}" "info: you successfully requested a safety backup of the server\"}]" # run safety backup CachedBackup "safety" - # spam protection - sleep 20s else 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\"}]" From 55da09d45619dcd100b44a3d363208e4494e1447 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 1 Jan 2022 17:56:47 +0100 Subject: [PATCH 086/115] fix: script safety function --- server.functions | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/server.functions b/server.functions index 45bd3d9..1140c86 100644 --- a/server.functions +++ b/server.functions @@ -168,19 +168,16 @@ function RootSafety { } # checks if a script is already running -# TODO: fix this mess (not working) function ScriptSafety { - if [[ ${force} == false ]]; then - declare -a scriptsLock=("backup.sh" "reset.sh" "restart.sh" "restore.sh" "start.sh" "stop.sh" "update.sh" "vent.sh") - scriptsLockLength=${#scripts[@]} - for ((i = 0; i < ${scriptsLockLength}; i++)); do - if pgrep --list-full ${scriptsLock[i]} | grep -q ${scriptsLock[i]} &>/dev/null; then - Print "warn" "script ${scriptsLock[i]} is already running" - Print "info" "use --force option to ignore this safety check" - exit 1 - fi - done - fi + declare -a scriptsLock=("backup.sh" "reset.sh" "restart.sh" "restore.sh" "start.sh" "stop.sh" "update.sh" "vent.sh") + scriptsLockLength=${#scripts[@]} + for ((i = 0; i < ${scriptsLockLength}; i++)); do + if pgrep --list-full "${scriptsLock[i]}" | grep -q "${scriptsLock[i]}"; then + Print "warn" "script ${scriptsLock[i]} is already running" + Print "info" "use --force option to ignore this safety check" + exit 1 + fi + done } # check for existance of screen terminal From a10af888fb860ec84ad58a83d9500edbf0f92082 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 1 Jan 2022 18:24:06 +0100 Subject: [PATCH 087/115] fix: script safety function now ignores itself as running process --- server.functions | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/server.functions b/server.functions index 1140c86..165c313 100644 --- a/server.functions +++ b/server.functions @@ -170,13 +170,15 @@ function RootSafety { # checks if a script is already running function ScriptSafety { declare -a scriptsLock=("backup.sh" "reset.sh" "restart.sh" "restore.sh" "start.sh" "stop.sh" "update.sh" "vent.sh") - scriptsLockLength=${#scripts[@]} + scriptsLockLength=${#scriptsLock[@]} for ((i = 0; i < ${scriptsLockLength}; i++)); do - if pgrep --list-full "${scriptsLock[i]}" | grep -q "${scriptsLock[i]}"; then - Print "warn" "script ${scriptsLock[i]} is already running" - Print "info" "use --force option to ignore this safety check" - exit 1 - fi + 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 } From 290190e8d07743b124b918f785514ae648c8cdcd Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 1 Jan 2022 18:29:53 +0100 Subject: [PATCH 088/115] fix: only check script safety if force is false --- server.functions | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/server.functions b/server.functions index 165c313..cb21f91 100644 --- a/server.functions +++ b/server.functions @@ -169,17 +169,19 @@ function RootSafety { # checks if a script is already running function ScriptSafety { - declare -a scriptsLock=("backup.sh" "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 + if [[ ${force} == false ]]; then + declare -a scriptsLock=("backup.sh" "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 - done + fi } # check for existance of screen terminal From 41cdf4b21067b6e0879f491b371cb79d52425f97 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 1 Jan 2022 18:30:57 +0100 Subject: [PATCH 089/115] fix: force start because of running process --- reset.sh | 8 ++++---- restart.sh | 8 ++++---- restore.sh | 8 ++++---- update.sh | 8 ++++---- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/reset.sh b/reset.sh index d6c1a8d..9ab8d5c 100644 --- a/reset.sh +++ b/reset.sh @@ -5,13 +5,13 @@ source server.settings source server.functions +# parse arguments +ParseArgs "$@" + # safety checks RootSafety ScriptSafety -# parse arguments -ParseArgs "$@" - # debug Debug "executing $0 script" @@ -50,7 +50,7 @@ mkdir world # restart the server echo "action" "restarting server..." -./start.sh "$@" +./start.sh --force "$@" # log to debug if true Debug "executed $0 script" diff --git a/restart.sh b/restart.sh index 4c3bbfe..9ef8ef0 100644 --- a/restart.sh +++ b/restart.sh @@ -5,13 +5,13 @@ source server.settings source server.functions +# parse arguments +ParseArgs "$@" + # safety checks RootSafety ScriptSafety -# parse arguments -ParseArgs "$@" - # debug Debug "executing $0 script" @@ -42,7 +42,7 @@ Print "ok" "server successfully stopped" # restart the server Print "action" "restarting server..." -./start.sh "$@" +./start.sh --force "$@" # log to debug if true Debug "executed $0 script" diff --git a/restore.sh b/restore.sh index 8219d10..669102a 100644 --- a/restore.sh +++ b/restore.sh @@ -5,13 +5,13 @@ source server.settings source server.functions +# parse arguments +ParseArgs "$@" + # safety checks RootSafety ScriptSafety -# parse arguments -ParseArgs "$@" - # debug Debug "executing $0 script" @@ -148,7 +148,7 @@ else Print "action" "restarting server..." Log "info" "backup restore has been canceled" "${screenLog}" Log "info" "resuming to current live world" "${screenLog}" - ./start.sh "$@" + ./start.sh --force "$@" fi # log to debug if true diff --git a/update.sh b/update.sh index 60f1717..805f705 100644 --- a/update.sh +++ b/update.sh @@ -5,13 +5,13 @@ source server.settings source server.functions +# parse arguments +ParseArgs "$@" + # safety checks RootSafety ScriptSafety -# parse arguments -ParseArgs "$@" - # debug Debug "executing $0 script" @@ -90,7 +90,7 @@ ExecutableScripts # restart the server Print "action" "restarting server..." -./start.sh "$@" +./start.sh --force "$@" # log to debug if true Debug "executed $0 script" From e2fa133d96941a60d6c13f31a4fdce1087a12205 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 1 Jan 2022 18:31:20 +0100 Subject: [PATCH 090/115] fix: parse script args first --- backup.sh | 8 ++++---- start.sh | 6 +++--- stop.sh | 6 +++--- vent.sh | 6 +++--- worker.sh | 6 +++--- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/backup.sh b/backup.sh index 6ba9fb3..d8e4484 100644 --- a/backup.sh +++ b/backup.sh @@ -9,10 +9,6 @@ source server.settings source server.functions -# safety checks -RootSafety -ScriptSafety - # parse backup category ParseCategory "$@" @@ -22,6 +18,10 @@ shift # parse arguments ParseArgs "$@" +# safety checks +RootSafety +ScriptSafety + # debug Debug "executing $0 script" diff --git a/start.sh b/start.sh index b0d16c1..3946d94 100644 --- a/start.sh +++ b/start.sh @@ -5,13 +5,13 @@ source server.settings source server.functions +# parse arguments +ParseArgs "$@" + # safety checks RootSafety ScriptSafety -# parse arguments -ParseArgs "$@" - # debug Debug "executing $0 script" diff --git a/stop.sh b/stop.sh index 31c3e30..49ccf40 100644 --- a/stop.sh +++ b/stop.sh @@ -5,13 +5,13 @@ source server.settings source server.functions +# parse arguments +ParseArgs "$@" + # safety checks RootSafety ScriptSafety -# parse arguments -ParseArgs "$@" - # debug Debug "executing $0 script" diff --git a/vent.sh b/vent.sh index 0038aa1..b8c73f8 100644 --- a/vent.sh +++ b/vent.sh @@ -7,13 +7,13 @@ source server.settings source server.functions +# parse arguments +ParseArgs "$@" + # safety checks RootSafety ScriptSafety -# parse arguments -ParseArgs "$@" - # debug Debug "executing $0 script" diff --git a/worker.sh b/worker.sh index a9f677e..c57d394 100644 --- a/worker.sh +++ b/worker.sh @@ -5,13 +5,13 @@ source server.settings source server.functions +# parse arguments +ParseArgs "$@" + # safety checks RootSafety ScriptSafety -# parse arguments -ParseArgs "$@" - # debug Debug "executing $0" From 12d8d1b2ecf39fb19fab4650b55be15fa281c8c3 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sat, 1 Jan 2022 18:35:35 +0100 Subject: [PATCH 091/115] fix: logging and printing order --- server.functions | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server.functions b/server.functions index cb21f91..5f3a498 100644 --- a/server.functions +++ b/server.functions @@ -196,8 +196,8 @@ function CheckScreen { # check for existance of screen terminal function LookForScreen { if screen -list | grep -q "\.${serverName}"; then - Log "warn" "server is already running - type screen -r ${serverName} to open server terminal" >>"${screenLog}" - Print "warn" "server is already running" + Log "warn" "server is already running" >>"${screenLog}" + Print "warn" "server is already running - type screen -r ${serverName} to open server terminal" exit 1 fi } From 02fb429811291c3bdd6671ccb3830c238a7b4837 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sun, 2 Jan 2022 11:01:22 +0100 Subject: [PATCH 092/115] feat: better java optimisation --- server.functions | 2 +- server.settings | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/server.functions b/server.functions index 5f3a498..b0a5fb3 100644 --- a/server.functions +++ b/server.functions @@ -283,7 +283,7 @@ function CheckPublic { # performs server start function Start { Print "action" "starting server..." - screen -dmSL "${serverName}" -Logfile "${screenLog}" java -server "${memory}" "${threads}" -jar "${executableServerFile}" -nogui + screen -dmSL "${serverName}" -Logfile "${screenLog}" java -server "${memory}" "${javaArgs}" -jar "${executableServerFile}" -nogui screen -r "${serverName}" -X colon "logfile flush 1^M" } diff --git a/server.settings b/server.settings index a3e1230..faabf79 100644 --- a/server.settings +++ b/server.settings @@ -10,6 +10,10 @@ 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") +# memory and arguments for java server +memory="-Xms2G -Xmx2G" +javaArgs="-XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 -XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch -XX:G1NewSizePercent=30 -XX:G1MaxNewSizePercent=40 -XX:G1HeapRegionSize=8M -XX:G1ReservePercent=20 -XX:G1HeapWastePercent=5 -XX:G1MixedGCCountTarget=4 -XX:InitiatingHeapOccupancyPercent=15 -XX:G1MixedGCLiveThresholdPercent=90 -XX:G1RSetUpdatingPauseTimePercent=5 -XX:SurvivorRatio=32 -XX:+PerfDisableSharedMem -XX:MaxTenuringThreshold=1" + # server resource paths serverName="replaceServerName" homeDirectory="replaceHomeDirectory" @@ -17,10 +21,6 @@ serverDirectory="replaceServerDirectory" backupDirectory="replaceBackupDirectory" executableServerFile="replaceExecutableServerFile" -# memory and threads for java server -memory="replaceMemory" -threads="replaceThreads" - # network public and private addresses public="replacePublic" private="replacePrivate" From 1e9df40368df7cdbc4e1992bd880ba50604779ab Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sun, 2 Jan 2022 11:28:03 +0100 Subject: [PATCH 093/115] feat: added help argument output --- server.functions | 47 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 7 deletions(-) diff --git a/server.functions b/server.functions index b0a5fb3..5f57d67 100644 --- a/server.functions +++ b/server.functions @@ -135,8 +135,22 @@ function ParseCategory { elif [[ $1 == "--monthly" ]]; then isMonthly=true else - Print "error" "$1 is not a backup category" + Print "error" "\"$1\" is not a backup category" Print "info" "use --hourly, --daily, --weekly, --monthly" + exit 1 + fi +} + +# 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 } @@ -170,7 +184,7 @@ function RootSafety { # checks if a script is already running function ScriptSafety { if [[ ${force} == false ]]; then - declare -a scriptsLock=("backup.sh" "reset.sh" "restart.sh" "restore.sh" "start.sh" "stop.sh" "update.sh" "vent.sh") + 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 @@ -184,6 +198,13 @@ function ScriptSafety { 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" +} + # check for existance of screen terminal function CheckScreen { if ! screen -list | grep -q "\.${serverName}"; then @@ -411,6 +432,8 @@ function OutputBackupSuccess { Print "ok" "current world size: ${worldSizeHuman}, current backup size: ${backupSizeHuman}, current disk space: ${diskSpaceHuman}" Print "ok" "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: ${backupSize}, current disk space: ${diskSpaceHuman}, time spent: ${timeSpent} ms, compression: ${compressedBackupSize}/${worldSizeHuman}" } @@ -420,6 +443,8 @@ function OutputDiskSpaceWarning { Print "warn" "free disk-space is getting rare - make some room for backups" + 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" } @@ -429,6 +454,8 @@ function OutputDiskSpaceError { Print "error" "not enough disk-space to perform backup-${1}" + 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" } @@ -438,6 +465,8 @@ function OutputBackupAlreadyExists { Print "error" "could not create new ${1}-backup - backup 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" } @@ -447,7 +476,9 @@ function OutputBackupTarError { Print "error" "tar reports errors during compression of world directory" - TellrawBackup "fatal: could not create new backup - please immediately tell your server admin" "red" "could not create file: ${serverName}-${1}.tar.gz, could not remove file: ${serverName}-${2}.tar.gz, reason: tar reports errors during compression of world directory" + Debug "backup script reports tar 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: tar reports errors during compression of world directory" } # prints generic backup error messages to terminal screen and backup log @@ -456,7 +487,9 @@ function OutputBackupGenericError { Print "error" "could not backup world" - TellrawBackup "fatal: could not create new backup - please immediately tell your server admin" "red" "could not create file: ${serverName}-${1}.tar.gz, could not remove file: ${serverName}-${2}.tar.gz, reason: generic error - missing directories, empty file-path or empty files" + Debug "backup script reports generic backup 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: generic error - missing directories, empty file-path or empty files" } # function for testing if all categories for backups exists if not create them also check for root backups directory @@ -497,10 +530,10 @@ function CachedBackup { # user info about backup to create Print "action" "creating cached ${1} backup..." # create backup with given name - nice -n 19 cp -r "world" "tmp" - nice -n 19 tar -czf "world.tar.gz" "tmp" + 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" + 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}" From ea7eb36ed419b0b78a4697cfd6b2e41a8ba320e1 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sun, 2 Jan 2022 11:28:29 +0100 Subject: [PATCH 094/115] fix: unified debug output --- backup.sh | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/backup.sh b/backup.sh index d8e4484..62a5f13 100644 --- a/backup.sh +++ b/backup.sh @@ -39,32 +39,28 @@ function RunBackup { Debug "executing backup-${1} script" if (((${worldSizeBytes} + ${diskSpaceError}) > ${diskSpaceBytes})); then OutputDiskSpaceError "${1}" "${2}" "${3}" - Debug "backup script reports not enough disk-space while performing backup-${1}" exit 1 fi if (((${worldSizeBytes} + ${diskSpaceWarning}) > ${diskSpaceBytes})); then - OutputDiskSpaceWarning - Debug "backup script reports low disk-space while performing backup-${1}" + OutputDiskSpaceWarning "${1}" fi if ! [[ -s "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" ]]; then Screen "save-off" sleep 1s before=$(date +%s%3N) - nice -n 19 cp -r "world" "tmp" - nice -n 19 tar -czf "world.tar.gz" "tmp" + nice -n 19 cp -r "world" "tmp-${1}" + nice -n 19 tar -czf "world.tar.gz" "tmp-${1}" if [ $? != 0 ]; then - OutputBackupTarError "${2}" "${3}" - Debug "backup script reports tar error while performing backup-${1}" + OutputBackupTarError "${1}" "${2}" "${3}" fi nice -n 19 mv "${serverDirectory}/world.tar.gz" "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" - nice -n 19 rm -r "tmp" + nice -n 19 rm -r "tmp-${1}" after=$(date +%s%3N) Screen "save-on" sleep 1s timeSpent=$((${after} - ${before})) else OutputBackupAlreadyExists "${1}" "${2}" "${3}" - Debug "backup script reports backup already exists while performing backup-${1}" exit 1 fi if [[ -s "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" ]]; then @@ -74,10 +70,8 @@ function RunBackup { compressedBackupSize=$(du -sh ${backupDirectory}/${1}/${serverName}-${2}.tar.gz | cut -f1) source server.settings OutputBackupSuccess "${1}" "${2}" "${3}" - Debug "backup script reports backup success while performing backup-${1}" else - OutputBackupGenericError "${2}" "${3}" - Debug "backup script reports backup error while performing backup-${1}" + OutputBackupGenericError "${1}" "${2}" "${3}" fi Debug "executed backup-${1} script" } From 7548f7bba3273fe5d321d999d1d48d0ff275adb4 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sun, 2 Jan 2022 11:28:54 +0100 Subject: [PATCH 095/115] feat: added argument help function to top --- backup.sh | 1 + reset.sh | 1 + restart.sh | 1 + restore.sh | 1 + start.sh | 1 + stop.sh | 1 + update.sh | 1 + vent.sh | 1 + worker.sh | 1 + 9 files changed, 9 insertions(+) diff --git a/backup.sh b/backup.sh index 62a5f13..50f5da4 100644 --- a/backup.sh +++ b/backup.sh @@ -17,6 +17,7 @@ shift # parse arguments ParseArgs "$@" +ArgHelp # safety checks RootSafety diff --git a/reset.sh b/reset.sh index 9ab8d5c..c8f627b 100644 --- a/reset.sh +++ b/reset.sh @@ -7,6 +7,7 @@ source server.functions # parse arguments ParseArgs "$@" +ArgHelp # safety checks RootSafety diff --git a/restart.sh b/restart.sh index 9ef8ef0..7950208 100644 --- a/restart.sh +++ b/restart.sh @@ -7,6 +7,7 @@ source server.functions # parse arguments ParseArgs "$@" +ArgHelp # safety checks RootSafety diff --git a/restore.sh b/restore.sh index 669102a..2fb2860 100644 --- a/restore.sh +++ b/restore.sh @@ -7,6 +7,7 @@ source server.functions # parse arguments ParseArgs "$@" +ArgHelp # safety checks RootSafety diff --git a/start.sh b/start.sh index 3946d94..8e9246f 100644 --- a/start.sh +++ b/start.sh @@ -7,6 +7,7 @@ source server.functions # parse arguments ParseArgs "$@" +ArgHelp # safety checks RootSafety diff --git a/stop.sh b/stop.sh index 49ccf40..bda3f9b 100644 --- a/stop.sh +++ b/stop.sh @@ -7,6 +7,7 @@ source server.functions # parse arguments ParseArgs "$@" +ArgHelp # safety checks RootSafety diff --git a/update.sh b/update.sh index 805f705..aa76b98 100644 --- a/update.sh +++ b/update.sh @@ -7,6 +7,7 @@ source server.functions # parse arguments ParseArgs "$@" +ArgHelp # safety checks RootSafety diff --git a/vent.sh b/vent.sh index b8c73f8..b9a78f9 100644 --- a/vent.sh +++ b/vent.sh @@ -9,6 +9,7 @@ source server.functions # parse arguments ParseArgs "$@" +ArgHelp # safety checks RootSafety diff --git a/worker.sh b/worker.sh index c57d394..1bb3069 100644 --- a/worker.sh +++ b/worker.sh @@ -7,6 +7,7 @@ source server.functions # parse arguments ParseArgs "$@" +ArgHelp # safety checks RootSafety From 8aa0573f697db1bd91ecbd5020439848872dd5f0 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sun, 2 Jan 2022 11:53:57 +0100 Subject: [PATCH 096/115] fix: reverting to old java arguments --- server.functions | 2 +- server.settings | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/server.functions b/server.functions index 5f57d67..f69b8a9 100644 --- a/server.functions +++ b/server.functions @@ -304,7 +304,7 @@ function CheckPublic { # performs server start function Start { Print "action" "starting server..." - screen -dmSL "${serverName}" -Logfile "${screenLog}" java -server "${memory}" "${javaArgs}" -jar "${executableServerFile}" -nogui + screen -dmSL "${serverName}" -Logfile "${screenLog}" java -server "${javaArgs}" -jar "${executableServerFile}" -nogui screen -r "${serverName}" -X colon "logfile flush 1^M" } diff --git a/server.settings b/server.settings index faabf79..fc359fa 100644 --- a/server.settings +++ b/server.settings @@ -10,9 +10,8 @@ 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") -# memory and arguments for java server -memory="-Xms2G -Xmx2G" -javaArgs="-XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 -XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch -XX:G1NewSizePercent=30 -XX:G1MaxNewSizePercent=40 -XX:G1HeapRegionSize=8M -XX:G1ReservePercent=20 -XX:G1HeapWastePercent=5 -XX:G1MixedGCCountTarget=4 -XX:InitiatingHeapOccupancyPercent=15 -XX:G1MixedGCLiveThresholdPercent=90 -XX:G1RSetUpdatingPauseTimePercent=5 -XX:SurvivorRatio=32 -XX:+PerfDisableSharedMem -XX:MaxTenuringThreshold=1" +# arguments for java server +javaArgs="-Xms1G -Xmx2G" # server resource paths serverName="replaceServerName" From 0de8fc2626862de50767ed710f8f86d7cdf4ec17 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sun, 2 Jan 2022 11:58:09 +0100 Subject: [PATCH 097/115] fix: set min mem and max mem equal --- server.settings | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.settings b/server.settings index fc359fa..9875992 100644 --- a/server.settings +++ b/server.settings @@ -11,7 +11,7 @@ adminContact="your admin did not edit the server settings file /:" 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="-Xms1G -Xmx2G" +javaArgs="-Xms2G -Xmx2G" # server resource paths serverName="replaceServerName" From 85de03e99cabab15cfad2bcc4479ac559b6db119 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sun, 2 Jan 2022 12:17:20 +0100 Subject: [PATCH 098/115] fix: some old variables --- server.functions | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server.functions b/server.functions index f69b8a9..2564024 100644 --- a/server.functions +++ b/server.functions @@ -424,7 +424,7 @@ function ChangeBackupDirectory { function OutputBackupSuccess { Log "ok" "added ${backupDirectory}/${1}/${serverName}-${2}.tar.gz" "${backupLog}" Log "ok" "removed ${backupDirectory}/${1}/${serverName}-${3}.tar.gz" "${backupLog}" - Log "ok" "current world size: ${worldSizeHuman}, current backup size: ${backupSizeHuman}, current disk space: ${diskspace}" "${backupLog}" + Log "ok" "current world size: ${worldSizeHuman}, current backup size: ${backupSizeHuman}, current disk space: ${diskSpaceHuman}" "${backupLog}" Log "ok" "time spent on backup process: ${timeSpent} milliseconds, compression ratio: ${compressedBackupSize}/${worldSizeHuman}" "${backupLog}" Print "ok" "added ${backupDirectory}/${1}/${serverName}-${2}.tar.gz" @@ -434,7 +434,7 @@ function OutputBackupSuccess { 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: ${backupSize}, current disk space: ${diskSpaceHuman}, time spent: ${timeSpent} ms, compression: ${compressedBackupSize}/${worldSizeHuman}" + 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 disk space warning to terminal screen and backup log From 132658fda5191d1f937c12b8d2eaf62b3bed6aee Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sun, 2 Jan 2022 12:23:02 +0100 Subject: [PATCH 099/115] fix: removed unused settings --- setup.sh | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/setup.sh b/setup.sh index e13a3a4..467fbe6 100644 --- a/setup.sh +++ b/setup.sh @@ -295,13 +295,6 @@ fi # store to settings Print "info" "storing variables in server.settings..." -StoreSettings "replacePublic" "1.1.1.1" -StoreSettings "replacePrivate" "192.168.1.1" -StoreSettings "replaceMemory" "-Xms2048M" -StoreSettings "replaceThreads" "-XX:ParallelGCThreads=4" -StoreSettings "replaceChangeToConsole" "false" -StoreSettings "replaceEnableWelcomeMessage" "true" -StoreSettings "replaceEnableBackupsWatchdog" "true" StoreSettings "replaceBranch" "${branch}" StoreSettings "replaceServerName" "${serverName}" StoreSettings "replaceHomeDirectory" "${homeDirectory}" @@ -318,6 +311,7 @@ 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 From 43a7070fa52fb219dbb85b7a24f2e46973d44bdc Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sun, 2 Jan 2022 12:23:28 +0100 Subject: [PATCH 100/115] chore: refactored and restructured --- server.settings | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/server.settings b/server.settings index 9875992..f827a75 100644 --- a/server.settings +++ b/server.settings @@ -4,6 +4,9 @@ # this file stores all the variables for the server. # if you know what you are doing, feel free to tinker with them ;^) +# github branch from whom scripts will fetch +branch="replaceBranch" + # your contact info for players adminContact="your admin did not edit the server settings file /:" @@ -11,7 +14,7 @@ adminContact="your admin did not edit the server settings file /:" 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" +javaArgs="-Xms2G -Xmx2G -XX:ParallelGCThreads=4" # server resource paths serverName="replaceServerName" @@ -21,8 +24,8 @@ backupDirectory="replaceBackupDirectory" executableServerFile="replaceExecutableServerFile" # network public and private addresses -public="replacePublic" -private="replacePrivate" +public="1.1.1.1" +private="192.168.1.1" # values in bytes for disk space control diskSpaceError="2097152" @@ -63,18 +66,16 @@ enablePerformRestart=true enablePerformUpdate=false enablePerformReset=false -# github branch from whom scripts will fetch -branch="replaceBranch" # enables or disable debug logging -enableDebug="replaceEnableDebug" +enableDebug=false # change to server console after startup -changeToConsole="replaceChangeToConsole" +changeToConsole=false # enables watchdog integrity checks for backups -enableBackupsWatchdog="replaceEnableBackupsWatchdog" +enableBackupsWatchdog=true # print welcome messages if a player joins -enableWelcomeMessage="replaceEnableWelcomeMessage" +enableWelcomeMessage=true # enables an autostart triggered by a server crash -enableAutoStartOnCrash="replaceEnableAutoStartOnCrash" +enableAutoStartOnCrash=true # terminal output colours black="$(tput setaf 0)" From 3fcd38adb361f7ce3e369e4d90a527eeec01c77d Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sun, 2 Jan 2022 12:25:09 +0100 Subject: [PATCH 101/115] chore: sum up advanced options --- server.settings | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/server.settings b/server.settings index f827a75..4e9e0db 100644 --- a/server.settings +++ b/server.settings @@ -14,7 +14,7 @@ adminContact="your admin did not edit the server settings file /:" 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=4" +javaArgs="-Xms2G -Xmx2G -XX:ParallelGCThreads=2" # server resource paths serverName="replaceServerName" @@ -66,15 +66,11 @@ enablePerformRestart=true enablePerformUpdate=false enablePerformReset=false -# enables or disable debug logging +# enables or disable some advanced options enableDebug=false -# change to server console after startup changeToConsole=false -# enables watchdog integrity checks for backups enableBackupsWatchdog=true -# print welcome messages if a player joins enableWelcomeMessage=true -# enables an autostart triggered by a server crash enableAutoStartOnCrash=true # terminal output colours From 15a404e2dc577a2e94a29e8d353407cde419817f Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Sun, 2 Jan 2022 16:14:47 +0100 Subject: [PATCH 102/115] feat: some update enhancements --- update.sh | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/update.sh b/update.sh index aa76b98..cb65446 100644 --- a/update.sh +++ b/update.sh @@ -54,8 +54,8 @@ if [ "$?" != 0 ]; then Log "warn" "unable to connect to mojang api skipping update..." "${screenLog}" Print "warn" "unable to connect to mojang api skipping update..." else - Log "info" "downloading newest server version..." "${screenLog}" - Print "ok" "downloading newest server version..." + Log "action" "downloading newest server version..." "${screenLog}" + Print "action" "downloading newest server version..." # check if already on newest version if [[ "${executableServerFile}" = *"minecraft-server.${version}.jar" ]]; then Log "info" "you are running the newest server version - skipping update" "${screenLog}" @@ -66,8 +66,10 @@ else newExecutableServerFile="${serverDirectory}/minecraft-server.${version}.jar" # if new serverfile exists remove oldserverfile if [ -s "${newExecutableServerFile}" ]; then - Log "ok" "updating server.settings for startup with new server version ${version}" "${screenLog}" - Print "ok" "updating server.settings for startup with new server version ${version}" + 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 [ -s "${executableServerFile}" ]; then From 4efe9375265e31753d385560d1dd057e984a3ce9 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 3 Jan 2022 21:22:49 +0100 Subject: [PATCH 103/115] fix: simultaneously doing backups should be possible now --- backup.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backup.sh b/backup.sh index 50f5da4..ae61f34 100644 --- a/backup.sh +++ b/backup.sh @@ -49,12 +49,12 @@ function RunBackup { Screen "save-off" sleep 1s before=$(date +%s%3N) - nice -n 19 cp -r "world" "tmp-${1}" - nice -n 19 tar -czf "world.tar.gz" "tmp-${1}" + nice -n 19 cp -r "world-${1}" "tmp-${1}" + nice -n 19 tar -czf "world-${1}.tar.gz" "tmp-${1}" if [ $? != 0 ]; then OutputBackupTarError "${1}" "${2}" "${3}" fi - nice -n 19 mv "${serverDirectory}/world.tar.gz" "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" + nice -n 19 mv "${serverDirectory}/world-${1}.tar.gz" "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" nice -n 19 rm -r "tmp-${1}" after=$(date +%s%3N) Screen "save-on" From eca7dc954a3e704d62ddd7657278a97e6d3c1dc8 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 3 Jan 2022 22:20:42 +0100 Subject: [PATCH 104/115] fix: fatal bug which blocks all backups --- backup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backup.sh b/backup.sh index ae61f34..b9f5ae9 100644 --- a/backup.sh +++ b/backup.sh @@ -49,7 +49,7 @@ function RunBackup { Screen "save-off" sleep 1s before=$(date +%s%3N) - nice -n 19 cp -r "world-${1}" "tmp-${1}" + nice -n 19 cp -r "world" "tmp-${1}" nice -n 19 tar -czf "world-${1}.tar.gz" "tmp-${1}" if [ $? != 0 ]; then OutputBackupTarError "${1}" "${2}" "${3}" From af5560eabbca8b18d4d2d5576c6ef2e83958eb4d Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 4 Jan 2022 22:10:51 +0100 Subject: [PATCH 105/115] feat: added backup copy error function --- server.functions | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/server.functions b/server.functions index 2564024..7afc622 100644 --- a/server.functions +++ b/server.functions @@ -481,6 +481,17 @@ function OutputBackupTarError { 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" } +# 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}" From 0838b40f13fa234a8922890d1fa89725a36e31e3 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Tue, 4 Jan 2022 22:11:13 +0100 Subject: [PATCH 106/115] feat: added safety checks for copy and compression --- backup.sh | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/backup.sh b/backup.sh index b9f5ae9..201d6fb 100644 --- a/backup.sh +++ b/backup.sh @@ -50,9 +50,16 @@ function RunBackup { sleep 1s before=$(date +%s%3N) nice -n 19 cp -r "world" "tmp-${1}" + if [ $? != 0 ]; then + OutputBackupCopyError "${1}" "${2}" "${3}" + rm -r "tmp-${1}" + exit 1 + fi 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 nice -n 19 mv "${serverDirectory}/world-${1}.tar.gz" "${backupDirectory}/${1}/${serverName}-${2}.tar.gz" nice -n 19 rm -r "tmp-${1}" From 7690a45fe21a064f3dfac345c840002de0482af8 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 6 Jan 2022 20:38:14 +0100 Subject: [PATCH 107/115] chore: chnaged ok logging and printing to info --- server.functions | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/server.functions b/server.functions index 7afc622..e967ed7 100644 --- a/server.functions +++ b/server.functions @@ -424,13 +424,13 @@ function ChangeBackupDirectory { function OutputBackupSuccess { Log "ok" "added ${backupDirectory}/${1}/${serverName}-${2}.tar.gz" "${backupLog}" Log "ok" "removed ${backupDirectory}/${1}/${serverName}-${3}.tar.gz" "${backupLog}" - Log "ok" "current world size: ${worldSizeHuman}, current backup size: ${backupSizeHuman}, current disk space: ${diskSpaceHuman}" "${backupLog}" - Log "ok" "time spent on backup process: ${timeSpent} milliseconds, compression ratio: ${compressedBackupSize}/${worldSizeHuman}" "${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}" Print "ok" "added ${backupDirectory}/${1}/${serverName}-${2}.tar.gz" Print "ok" "removed ${backupDirectory}/${1}/${serverName}-${3}.tar.gz" - Print "ok" "current world size: ${worldSizeHuman}, current backup size: ${backupSizeHuman}, current disk space: ${diskSpaceHuman}" - Print "ok" "time spent on backup process: ${timeSpent} milliseconds, compression ratio: ${compressedBackupSize}/${worldSizeHuman}" + 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}" From f40f9c7611dc9234654dc4266d50dbcf8bf46522 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 6 Jan 2022 21:52:00 +0100 Subject: [PATCH 108/115] feat: added backup size control --- server.settings | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/server.settings b/server.settings index 4e9e0db..3f19e2b 100644 --- a/server.settings +++ b/server.settings @@ -27,10 +27,6 @@ executableServerFile="replaceExecutableServerFile" public="1.1.1.1" private="192.168.1.1" -# values in bytes for disk space control -diskSpaceError="2097152" -diskSpaceWarning="8208608" - # logfile names screenLog="screen.log" backupLog="backup.log" @@ -42,6 +38,14 @@ 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=20 +backupSizeWarning=40 + # backup file formats newHourly=$(date +"%H:00") newDaily=$(date +"%Y-%m-%d") @@ -69,9 +73,9 @@ enablePerformReset=false # enables or disable some advanced options enableDebug=false changeToConsole=false -enableBackupsWatchdog=true enableWelcomeMessage=true -enableAutoStartOnCrash=true +enableBackupsWatchdog=true +enableAutoStartOnCrash=false # terminal output colours black="$(tput setaf 0)" From f2d4fcc949738e060070a5937e7e2c8ba2b3310f Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 6 Jan 2022 21:52:59 +0100 Subject: [PATCH 109/115] feat: added backup size safety checks --- backup.sh | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/backup.sh b/backup.sh index 201d6fb..b03c0c7 100644 --- a/backup.sh +++ b/backup.sh @@ -76,6 +76,14 @@ function RunBackup { nice -n 19 rm "${backupDirectory}/${1}/${serverName}-${3}.tar.gz" fi compressedBackupSize=$(du -sh ${backupDirectory}/${1}/${serverName}-${2}.tar.gz | cut -f1) + compressedBackupSizeBytes=$(du -s ${backupDirectory}/${1}/${serverName}-${2}.tar.gz | cut -f1) + if ((${compressedBackupSizeBytes} < (${worldSizeBytes} / 100 * ${backupSizeError}))); then + OutputBackupSizeError "${1}" "${2}" "${3}" + exit 1 + fi + if ((${compressedBackupSizeBytes} < (${worldSizeBytes} / 100 * ${backupSizeWarning}))); then + OutputBackupSizeWarning "${1}" "${2}" "${3}" + fi source server.settings OutputBackupSuccess "${1}" "${2}" "${3}" else From c5cb27432d4b746f8bc7f461be1dae532cb54e24 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 6 Jan 2022 21:53:23 +0100 Subject: [PATCH 110/115] chore: more comments for explanation --- backup.sh | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/backup.sh b/backup.sh index b03c0c7..5d09c09 100644 --- a/backup.sh +++ b/backup.sh @@ -38,52 +38,65 @@ BackupDirectoryIntegrity # 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 is getting low if (((${worldSizeBytes} + ${diskSpaceWarning}) > ${diskSpaceBytes})); then OutputDiskSpaceWarning "${1}" fi + # 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) + # copy world nice -n 19 cp -r "world" "tmp-${1}" if [ $? != 0 ]; then OutputBackupCopyError "${1}" "${2}" "${3}" rm -r "tmp-${1}" exit 1 fi + # 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 + # 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 - timeSpent=$((${after} - ${before})) 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) + # 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 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 From d8fb9d6079026ddd26e182417b65d84efb5e9de0 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 6 Jan 2022 21:53:55 +0100 Subject: [PATCH 111/115] feat: added backup size control functions --- server.functions | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/server.functions b/server.functions index e967ed7..c705cc0 100644 --- a/server.functions +++ b/server.functions @@ -448,6 +448,19 @@ function OutputDiskSpaceWarning { 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 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}" @@ -459,6 +472,19 @@ function OutputDiskSpaceError { 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 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 already exists messages to terminal screen and backup log function OutputBackupAlreadyExists { Log "error" "could not create new ${1}-backup - backup already exists" "${backupLog}" From 4d7eacb45a4bab2523ff892f97d1918312e212be Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 6 Jan 2022 21:54:24 +0100 Subject: [PATCH 112/115] chore: various logging infos and typos --- server.functions | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/server.functions b/server.functions index c705cc0..6724d61 100644 --- a/server.functions +++ b/server.functions @@ -440,8 +440,10 @@ function OutputBackupSuccess { # 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}" @@ -464,8 +466,10 @@ function OutputBackupSizeWarning { # 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" Debug "backup script reports not enough disk-space while performing backup-${1}" @@ -488,8 +492,10 @@ function OutputBackupSizeError { # 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}" @@ -526,7 +532,7 @@ function OutputBackupGenericError { Debug "backup script reports generic backup 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: generic error - missing directories, empty file-path or empty files" + 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 From 166b0e05ee5f9851b2930198b801bc819226ef9f Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Thu, 6 Jan 2022 22:11:11 +0100 Subject: [PATCH 113/115] chore: backup size check broken --- backup.sh | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/backup.sh b/backup.sh index 5d09c09..8d07dfc 100644 --- a/backup.sh +++ b/backup.sh @@ -87,13 +87,15 @@ function RunBackup { 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 + if ((${compressedBackupSizeBytes} < (${worldSizeBytes} / (100 * ${backupSizeError})))); then OutputBackupSizeError "${1}" "${2}" "${3}" exit 1 fi + # TODO: fix this buggy mess # check if backup size is suspiciously small - if ((${compressedBackupSizeBytes} < (${worldSizeBytes} / 100 * ${backupSizeWarning}))); then + if ((${compressedBackupSizeBytes} < (${worldSizeBytes} / (100 * ${backupSizeWarning})))); then OutputBackupSizeWarning "${1}" "${2}" "${3}" fi # read settings and output success From 3b86e0c352ff7412d3f425b0a1d95ca9d052c461 Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 10 Jan 2022 10:08:23 +0100 Subject: [PATCH 114/115] chore: temporary fix for backup sizes --- server.settings | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server.settings b/server.settings index 3f19e2b..d1b7cbe 100644 --- a/server.settings +++ b/server.settings @@ -43,8 +43,8 @@ diskSpaceError=2097152 diskSpaceWarning=8208608 # values in percent for backup size control -backupSizeError=20 -backupSizeWarning=40 +backupSizeError=200 +backupSizeWarning=400 # backup file formats newHourly=$(date +"%H:00") From 0f748f5f6dbe8cc6dd95e1fb401c3341d3b310de Mon Sep 17 00:00:00 2001 From: simylein <67859356+simylein@users.noreply.github.com> Date: Mon, 10 Jan 2022 10:10:26 +0100 Subject: [PATCH 115/115] feat: new readme --- README.md | 177 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 176 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ab06037..e5996c2 100644 --- a/README.md +++ b/README.md @@ -1 +1,176 @@ -TODO: write new README +# 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. + +## 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. + +``` +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. + +## 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` +
+If you want to resume a certain screen session just type: `screen -r ${servername}` + +If you would like to scroll inside a screen session press Ctrl+A and Esc (enter copy mode).
+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. + +`whitelist add ${playername}` adding someone to your whitelist so he/she can join your server.
+`whitelist remove ${playername}` remove someone to your whitelist so he/she can no longer join your server.
+`op ${playername}` make someone admin on your server so he/she can execute commands.
+`deop ${playername}` remove admin permissions for a player so he/she can no longer execute commands.
+`ban ${playername}` ban someone from your server so he/she can no longer join your server.
+`pardon ${playername}` pardon someone from your server so he/she can join your server.
+`tp ${playername} ${x} ${y} ${z}` teleporting a player to cords.
+`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. + +## 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. +# If you know what you are doing, feel free to tinker with them ;^) + +# command line 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)" +... +``` + +## server.properties + +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]
+`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 -verbose` +Example: `./start.sh -now` + +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:
+ +First star: Minutes [0 - 59]
+Secound star: Hours [0 - 23]
+Third star: Day of Month [0 - 31]
+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. + +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 ;^) + +Best regards,
+Simylein