#!/bin/bash

worlds_dir="/home/vhadmin/.config/unity3d/IronGate/Valheim/worlds"

if [[ -z $1 ]]; then
    echo "Usage: $0 backup_dir"
    exit 2
fi
backup_dir="$1"

# Check if directory exists
if [[ ! -d "$backup_dir" ]]; then
    echo "Error: directory \"$backup_dir\" not found."
    exit 1
fi

# Check if server is active
status=$(systemctl show valheim -p ActiveState --value)
# shutdown server if it is active
if [[ $status == active ]]; then
    echo "Server is active: executing shutdown..."
    systemctl stop valheim
    sleep 1
fi

# if worlds dir is non-empty, save it as worlds.bak
if [[ ! -z $(ls $worlds_dir) ]]; then
    echo "Worlds directory is nonempty: saving backup as $worlds_dir.bak"
    if [[ -e $worlds_dir.bak ]]; then
        rm -r $worlds_dir.bak
    fi
    mv $worlds_dir $worlds_dir.bak
    mkdir $worlds_dir
    chown $(stat -c %U:%G $worlds_dir.bak) $worlds_dir
fi

# copy backup to worlds_dir
echo "Copying worlds from backup directory..."
rsync -aSH "$backup_dir/" $worlds_dir/

# start server back up if it was active
if [[ $status == active ]]; then
    echo "Server was active: starting server again..."
    systemctl start valheim
    sleep 5
fi

echo "Done!"