#!/bin/bash

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

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

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

# hour at which to do daily tasks
dailyhour=4

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

if [[ 10#$hour -eq $dailyhour ]]; then
    systemctl stop valheim
    sleep 1
fi
    
# hourly backup
rm_ife worlds-hourly-$hour
vh-backup worlds-hourly-$hour

if [[ 10#$hour -eq $dailyhour ]]; then
    systemctl start valheim
    
    # 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