#!/bin/bash

DIR_TO_BACKUP="/home/mcserver/mc-papermc-server"
BACKUP_DEST="/opt/backups/papermc-server"
SERVICE_NAME="mcserver-papermc.service"

systemctl is-active --quiet $SERVICE_NAME

if [ $? -ne 0 ]; then
	echo "Service not running."
	echo "Skipping shutdown procedure."
else
	echo "Notifying players"
	/usr/local/bin/mcrcon -H 5.161.249.43 -p 5eXeERr4Tkg6kAxc4U 'say Restarting in 5 minutes for backup...'
	sleep 300

	/usr/local/bin/mcrcon -H 5.161.249.43 -p 5eXeERr4Tkg6kAxc4U 'say Restarting in 30 seconds for backup...'
	sleep 30

	echo "Stopping $SERVICE_NAME"
	systemctl stop $SERVICE_NAME
	if [ $? -ne 0 ]; then
	    echo "Couldn't stop service. Exiting."
	    exit 1
	fi
fi


CURRENT_DATE=$(date +%Y-%m-%d_%H-%M)
echo "Creating $BACKUP_DEST/$CURRENT_DATE.tar.gz"
tar -czf "$BACKUP_DEST/$CURRENT_DATE.tar.gz" "$DIR_TO_BACKUP"
if [ $? -ne 0 ]; then
    echo "Couldn't create backup. Exiting."
    exit 1
fi


echo "Starting $SERVICE_NAME"
systemctl start $SERVICE_NAME
if [ $? -ne 0 ]; then
    echo "Couldn't start service. Exiting."
    exit 1
fi


# Delete old backups if there are more than 10
if [ $(ls $BACKUP_DEST/*.tar.gz | wc -l) -gt 10 ]
then
    echo "Files to clean up: "
    ls -t $BACKUP_DEST/*.tar.gz | tail -n 1
    ls -t $BACKUP_DEST/*.tar.gz | tail -n 1 | xargs rm
fi


echo "Backup successful."
