#!/bin/bash do_stop() { echo "Shutting down server for scheduled daily backup." mcbe-shutdown 10 "Shutting down server for scheduled daily backup." } do_start() { sleep 5 echo "Restarting server after backup." service mcbe start } do_backup() { day=$(date +%d) cd /vol/data mkdir -p worlds-daily-$day/ rsync -vaSH /home/mcadmin/worlds/ worlds-daily-$day/ if [[ $day == 1 ]]; then month=$(date +%m) year=$(date +%Y) mkdir -p worlds-$year-$month-$day/ rsync -vaSH worlds-daily-$day/ worlds-$year-$month-$day/ fi } # Check if server is started status=$(systemctl show mcbe -p ActiveState --value) # Check if any players present players=$(mcbe-exec list | cut -d ' ' -f 3 | cut -d '/' -f 1) # check when mcbe-backup was last triggered last=$(date -d "$(systemctl show mcbe-backup.timer -p LastTriggerUSec --value)" +%s) # get current time now=$(date +%s) # if service is not active, do backup immediately and exit if [[ $status != active ]]; then echo "Service is inactive: copying worlds immediately without restarting service." do_backup # if no players are present, do backup immediately and exit elif [[ $players == 0 ]]; then echo "No players detected: running backup immediately." do_stop do_backup do_start # if 12 or more hours have passed since backup was triggered, go ahead and force a shutdown anyways elif [[ $(( $now - $last )) -ge 43200 ]]; then echo "Backup was triggered more than 12 hours ago: forcing backup now." do_stop do_backup do_start # otherwise, schedule another attempt in an hour else echo "Players present in server: rescheduling backup to one hour from now." systemd-run --on-active=1h $0 fi