#!/bin/bash

rm_ife() {
    if [[ -e "$1" ]]; then
        rm -r "$1"
    fi
}

# Check if server is started
status=$(systemctl show mcbe -p ActiveState --value)
if [[ $status != active ]]; then
    echo "mcbe.service is inactive. Exiting."
    exit 1
fi

# get time
hour=$(date +%H)
day=$(date +%d)
month=$(date +%m)
year=$(date +%Y)

# cd to backup dir
cd /vol/data/backup

# hourly backup
mcbe-exec say "Autosaving..."
rm_ife worlds-hourly-$hour
mcbe-backup worlds-hourly-$hour

# 10#$var construction is to force base-10 interpretation of variable
# because otherwise, numbers starting with 0 are interpreted as octal
if [[ 10#$hour -eq 1 ]]; then
    # if no players are present, restart the server
    # should help deal with any memory leaks or other bugs
    players=""
    tries=0
    while [[ -z $players ]]; do
        if [[ $tries -eq 10 ]]; then
            echo "Error: failed to get number of players present after 10 tries."
            players=10
            break
        fi
        players=$(mcbe-exec list | head -n 1 | cut -d ' ' -f 3 | cut -d '/' -f 1)
    done
    if [[ $players -eq 0 ]]; then
	mcbe-restart
    fi

    # save daily and longterm backups
    rm_ife worlds-daily-$day.zip
    zip -rT worlds-daily-$day.zip worlds-hourly-$hour
    chown "$(stat -c '%U:%G' worlds-hourly-$hour)" worlds-daily-$day.zip
    touch -d "$(stat -c '%y' worlds-hourly-$hour)" worlds-daily-$day.zip
    if [[ 10#$day -eq 1 ]]; then
	cp -a worlds-daily-$day.zip worlds-$year-$month-$day.zip
    fi
fi