#!/bin/bash

# Nextcloud Restoration Script
# Created: $(date)
# Backup File: nextcloud_backup_20250831_181733.tar.gz

set -e

BACKUP_FILE="/srv/mergerfs/DataPool/nextcloud_backup_20250831_181733.tar.gz"
RESTORE_DIR="/export"
NEXTCLOUD_CONTAINER="nextcloud_nextcloud.1.p2nf122a4g6k4xt16e50zampc"

echo "=== Nextcloud Restoration Script ==="
echo "Backup file: $BACKUP_FILE"
echo "Restore directory: $RESTORE_DIR"
echo ""

# Check if backup file exists
if [ ! -f "$BACKUP_FILE" ]; then
    echo "ERROR: Backup file not found: $BACKUP_FILE"
    exit 1
fi

# Check if restore directory exists
if [ ! -d "$RESTORE_DIR" ]; then
    echo "ERROR: Restore directory not found: $RESTORE_DIR"
    exit 1
fi

echo "Step 1: Stopping Nextcloud container..."
docker service scale nextcloud=0 || echo "Warning: Could not stop Nextcloud service"

echo "Step 2: Creating backup of current Nextcloud (if exists)..."
if [ -d "$RESTORE_DIR/nextcloud" ]; then
    mv "$RESTORE_DIR/nextcloud" "$RESTORE_DIR/nextcloud.old.$(date +%Y%m%d_%H%M%S)"
fi

echo "Step 3: Extracting backup..."
cd "$RESTORE_DIR"
tar -xzf "$BACKUP_FILE"

echo "Step 4: Setting correct permissions..."
chown -R 33:33 "$RESTORE_DIR/nextcloud" 2>/dev/null || echo "Warning: Could not set ownership"
chmod -R 755 "$RESTORE_DIR/nextcloud" 2>/dev/null || echo "Warning: Could not set permissions"

echo "Step 5: Starting Nextcloud service..."
docker service scale nextcloud=1

echo "Step 6: Waiting for container to start..."
sleep 10

echo "Step 7: Running Nextcloud maintenance commands..."
docker exec "$NEXTCLOUD_CONTAINER" php /var/www/html/occ maintenance:mode --off 2>/dev/null || echo "Warning: Could not disable maintenance mode"
docker exec "$NEXTCLOUD_CONTAINER" php /var/www/html/occ files:scan --all 2>/dev/null || echo "Warning: Could not scan files"

echo ""
echo "=== Restoration Complete ==="
echo "Nextcloud should now be accessible at: https://nextcloud.pressmess.duckdns.org"
echo ""
echo "If you encounter issues:"
echo "1. Check container logs: docker service logs nextcloud"
echo "2. Check permissions: ls -la $RESTORE_DIR/nextcloud"
echo "3. Run maintenance: docker exec $NEXTCLOUD_CONTAINER php /var/www/html/occ maintenance:install --database-host=nextcloud-db --database=nextcloud1 --database-user=nextcloud --database-pass=YourStrongDatabasePasswordHere"
echo ""
echo "Old Nextcloud directory (if exists): $RESTORE_DIR/nextcloud.old.*"
