Files
external-minecraft/roles/minecraft-podman/templates/restore.sh.j2
2026-09-02 14:47:08 -06:00

107 lines
2.7 KiB
Django/Jinja

#!/bin/bash
#
# Minecraft Server Restore Script
# Deployed by Ansible - managed file
#
# Usage: ./restore.sh [path_to_backup_file]
# If no argument given, restores the most recent backup.
#
# WARNING: This will OVERWRITE the current world data!
#
set -euo pipefail
# Configuration
DATA_DIR="{{ paths.data_dir }}"
BACKUP_DIR="{{ paths.backup_dir }}"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
log() {
echo -e "$(date '+%Y-%m-%d %H:%M:%S') $*"
}
error() {
log "${RED}[ERROR]${NC} $*"
exit 1
}
warn() {
log "${YELLOW}[WARN]${NC} $*"
}
ok() {
log "${GREEN}[OK]${NC} $*"
}
# Determine which backup to restore
if [ $# -eq 1 ]; then
# Explicit file provided
RESTORE_FILE="$1"
if [ ! -f "$RESTORE_FILE" ]; then
# Try to find it in the backup dir
RESTORE_FILE="${BACKUP_DIR}/$1"
if [ ! -f "$RESTORE_FILE" ]; then
error "Backup file not found: $1 (looked in $BACKUP_DIR)"
fi
fi
else
# Find most recent backup
RESTORE_FILE=$(ls -t "${BACKUP_DIR}/"{{ minecraft.server_name }}_*.tar* 2>/dev/null | head -n1)
if [ -z "$RESTORE_FILE" ]; then
error "No backups found in $BACKUP_DIR"
fi
fi
log "Selected backup: $RESTORE_FILE"
# Double-check safety
warn "This will overwrite the current Minecraft world data in $DATA_DIR"
read -p "Are you sure you want to continue? (yes/no): " CONFIRM
if [ "$CONFIRM" != "yes" ]; then
log "Aborting restore."
exit 1
fi
# Stop the Minecraft server if running
if podman ps --format '{% raw %}{{.Names}}{% endraw %}' | grep -q '{{ podman_container_name }}'; then
warn "Stopping Minecraft server container..."
systemctl stop {{ minecraft.server_name }}
sleep 3
warn "Server stopped."
fi
# Create a temporary backup of current state (safety net)
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
SAFETY_BACKUP="${BACKUP_DIR}/pre_restore_${TIMESTAMP}.tar.gz"
log "Creating safety backup of current state: $SAFETY_BACKUP"
tar -czf "$SAFETY_BACKUP" -C "$(dirname $DATA_DIR)" "$(basename $DATA_DIR)"
# Extract the restore file
log "Restoring from: $RESTORE_FILE"
case "$RESTORE_FILE" in
*.tar.gz|*.tgz)
tar -xzf "$RESTORE_FILE" -C "$(dirname $DATA_DIR)"
;;
*.tar)
tar -xf "$RESTORE_FILE" -C "$(dirname $DATA_DIR)"
;;
*)
error "Unsupported archive format: $RESTORE_FILE"
;;
esac
ok "Restore completed successfully!"
# Restart the server
log "Restarting Minecraft server..."
systemctl start {{ minecraft.server_name }}
sleep 5
ok "Server restarted. Verify it's running: systemctl status {{ minecraft.server_name }}"
log "A safety backup of the pre-restore state was saved to: $SAFETY_BACKUP"