postgres-service/scripts/restore.sh

95 lines
2.9 KiB
Bash

#!/bin/bash
# PostgreSQL Restore Script for Proxmox LXC Container
# Check if backup file is provided
if [ $# -ne 1 ]; then
echo "Usage: $0 <backup-file>"
echo "Example: $0 ../backups/postgres_backup_20250419_120000.sql.gz"
echo " $0 ../backups/postgres_volume_backup_20250419_120000.tar.gz"
exit 1
fi
BACKUP_FILE=$1
# Check if backup file exists
if [ ! -f "${BACKUP_FILE}" ]; then
echo "Error: Backup file '${BACKUP_FILE}' not found!"
exit 1
fi
# Load environment variables
if [ -f ../.env ]; then
source ../.env
else
echo "Error: .env file not found!"
exit 1
fi
# Set default values if not provided in .env
POSTGRES_USER=${POSTGRES_USER:-"postgres"}
POSTGRES_DB=${POSTGRES_DB:-"postgres"}
echo "Starting PostgreSQL restore..."
echo "Database: ${POSTGRES_DB}"
echo "Backup file: ${BACKUP_FILE}"
# Determine backup type (SQL dump or volume backup)
if [[ "${BACKUP_FILE}" == *"postgres_backup_"* ]]; then
# SQL dump restore
# Confirm restore operation
read -p "Warning: This will overwrite the existing database. Continue? (y/n): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Restore operation cancelled."
exit 0
fi
# Perform the restore
echo "Restoring database from SQL dump..."
gunzip -c ${BACKUP_FILE} | docker exec -i postgres psql -U ${POSTGRES_USER} -d ${POSTGRES_DB}
# Check if restore was successful
if [ $? -eq 0 ]; then
echo "Restore completed successfully from: ${BACKUP_FILE}"
else
echo "Error: Restore failed!"
exit 1
fi
elif [[ "${BACKUP_FILE}" == *"postgres_volume_backup_"* ]]; then
# Volume backup restore
# Confirm restore operation
read -p "WARNING: This will completely replace the PostgreSQL data volume. All current data will be lost. Continue? (y/n): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Restore operation cancelled."
exit 0
fi
echo "Stopping PostgreSQL container..."
docker-compose down
echo "Restoring volume data from backup..."
# Create a temporary container to restore the volume
docker run --rm -v postgres_data:/data -v $(pwd)/$(dirname ${BACKUP_FILE}):/backup alpine sh -c "rm -rf /data/* && tar -xzf /backup/$(basename ${BACKUP_FILE}) -C / --strip-components=1"
# Check if restore was successful
if [ $? -eq 0 ]; then
echo "Volume restore completed successfully from: ${BACKUP_FILE}"
echo "Starting PostgreSQL container..."
docker-compose up -d
echo "Waiting for PostgreSQL to start..."
sleep 10
echo "PostgreSQL service restored and running."
else
echo "Error: Volume restore failed!"
echo "Starting PostgreSQL container..."
docker-compose up -d
exit 1
fi
else
echo "Error: Unknown backup file format. Expected postgres_backup_*.sql.gz or postgres_volume_backup_*.tar.gz"
exit 1
fi
exit 0