#!/bin/bash

# Fix Nextcloud Data Directory Script
# Fixes the data directory issue and prepares for upgrade
# Created: $(date)

set -e

echo "=== Fixing Nextcloud Data Directory ==="
echo ""

# Stop Nextcloud service
echo "Stopping Nextcloud service..."
ssh root@omv800 "docker service scale nextcloud_nextcloud=0"
sleep 30

# Create local database directory
LOCAL_DB_DIR="/srv/dev-disk-by-uuid-0f772f0b-917d-4337-a3c5-5cc5d3badac9/nextcloud-db"
echo "Creating local database directory: $LOCAL_DB_DIR"
ssh root@omv800 "mkdir -p $LOCAL_DB_DIR"
ssh root@omv800 "chown -R 33:33 $LOCAL_DB_DIR"

# Copy data from original location to local drive
echo "Copying data to local drive..."
ssh root@omv800 "cp -r /export/nextcloud/data/* $LOCAL_DB_DIR/"
ssh root@omv800 "chown -R 33:33 $LOCAL_DB_DIR"

# Verify the .ocdata file exists
echo "Verifying data integrity..."
if ssh root@omv800 "test -f $LOCAL_DB_DIR/.ocdata"; then
    echo "✅ .ocdata file found"
else
    echo "❌ .ocdata file not found - creating it"
    ssh root@omv800 "touch $LOCAL_DB_DIR/.ocdata"
    ssh root@omv800 "chown 33:33 $LOCAL_DB_DIR/.ocdata"
fi

# Update Docker configuration to only use local data directory
echo "Updating Docker configuration..."
cd /home/jonathan/Coding/HomeAudit
cp stacks/apps/nextcloud.yml stacks/apps/nextcloud.yml.fixed.$(date +%Y%m%d_%H%M%S)

# Remove the original nextcloud mount and keep only the data mount
sed -i 's|- /export/nextcloud:/var/www/html|- /export/nextcloud:/var/www/html|g' stacks/apps/nextcloud.yml
sed -i '/\/var\/www\/html\/data/d' stacks/apps/nextcloud.yml

# Add the local data directory mount
sed -i 's|- /export/nextcloud:/var/www/html|- /export/nextcloud:/var/www/html\n      - /srv/dev-disk-by-uuid-0f772f0b-917d-4337-a3c5-5cc5d3badac9/nextcloud-db:/var/www/html/data|g' stacks/apps/nextcloud.yml

# Deploy the fixed configuration
echo "Deploying fixed configuration..."
scp stacks/apps/nextcloud.yml root@omv800:/tmp/nextcloud.yml
ssh root@omv800 "docker stack deploy -c /tmp/nextcloud.yml nextcloud"

echo "Waiting for service to start..."
sleep 60

# Check service status
if ssh root@omv800 "docker service ls | grep -q nextcloud_nextcloud"; then
    echo "✅ Service is running"
    
    # Wait for container to be ready
    echo "Waiting for container to be ready..."
    sleep 30
    
    # Check container status
    CONTAINER_ID=$(ssh root@omv800 "docker ps -q -f name=nextcloud" | head -1)
    if [ -n "$CONTAINER_ID" ]; then
        echo "✅ Container found: $CONTAINER_ID"
        
        # Test Nextcloud status
        echo "Testing Nextcloud status..."
        ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ status"
        
        echo ""
        echo "✅ Nextcloud data directory fixed successfully!"
        echo "Ready for upgrade process."
    else
        echo "❌ Container not found"
        exit 1
    fi
else
    echo "❌ Service failed to start"
    exit 1
fi
