#!/bin/bash

# Simple Nextcloud Upgrade Script
# Upgrades from 27.1.3 to 31.0.8 with database migration
# Created: $(date)

set -e

echo "=== Simple Nextcloud Upgrade Script ==="
echo "Upgrading from 27.1.3 to 31.0.8"
echo ""

# Function to get container ID
get_container_id() {
    ssh root@omv800 "docker ps -q -f name=nextcloud" | head -1
}

# Function to wait for container
wait_for_container() {
    echo "Waiting for Nextcloud container to be ready..."
    for i in {1..30}; do
        CONTAINER_ID=$(get_container_id)
        if [ -n "$CONTAINER_ID" ]; then
            echo "✅ Container found: $CONTAINER_ID"
            return 0
        fi
        echo "Waiting... ($i/30)"
        sleep 10
    done
    echo "❌ Container not found after 5 minutes"
    return 1
}

# Step 1: Check current status
echo "=== STEP 1: CHECKING CURRENT STATUS ==="
CONTAINER_ID=$(get_container_id)
if [ -z "$CONTAINER_ID" ]; then
    echo "Starting Nextcloud service..."
    ssh root@omv800 "docker service scale nextcloud_nextcloud=1"
    wait_for_container || exit 1
    CONTAINER_ID=$(get_container_id)
fi

echo "Current container: $CONTAINER_ID"

# Check current version
echo "Checking current version..."
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ status"

# Check database type
echo "Checking database configuration..."
DB_TYPE=$(ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ config:list system" | grep '"dbtype"' | cut -d'"' -f4)
echo "Database type: $DB_TYPE"

# Step 2: Database Migration (if SQLite3)
if [ "$DB_TYPE" = "sqlite3" ]; then
    echo ""
    echo "=== STEP 2: DATABASE MIGRATION ==="
    echo "Migrating database from MergerFS to local drive..."
    
    # Stop 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 database
    echo "Copying database to local drive..."
    ssh root@omv800 "cp -r /export/nextcloud/data/* $LOCAL_DB_DIR/"
    ssh root@omv800 "chown -R 33:33 $LOCAL_DB_DIR"
    
    # Update configuration
    echo "Updating Docker configuration..."
    cd /home/jonathan/Coding/HomeAudit
    cp stacks/apps/nextcloud.yml stacks/apps/nextcloud.yml.backup.$(date +%Y%m%d_%H%M%S)
    
    # Add local database volume
    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 with local database
    echo "Deploying with local database..."
    scp stacks/apps/nextcloud.yml root@omv800:/tmp/nextcloud.yml
    ssh root@omv800 "docker stack deploy -c /tmp/nextcloud.yml nextcloud"
    
    # Wait for container
    wait_for_container || exit 1
    CONTAINER_ID=$(get_container_id)
    
    echo "✅ Database migration completed"
fi

# Step 3: Create backup
echo ""
echo "=== STEP 3: CREATING BACKUP ==="
BACKUP_FILE="/export/nextcloud_backups/nextcloud_backup_$(date +%Y%m%d_%H%M%S).tar.gz"
echo "Creating backup: $BACKUP_FILE"
ssh root@omv800 "mkdir -p /export/nextcloud_backups"
ssh root@omv800 "cd /export && tar -czf $BACKUP_FILE nextcloud/"
echo "✅ Backup created"

# Step 4: Upgrade to Nextcloud 31
echo ""
echo "=== STEP 4: UPGRADING TO NEXTCLOUD 31 ==="

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

# Update configuration
echo "Updating to Nextcloud 31..."
cd /home/jonathan/Coding/HomeAudit
sed -i 's|image: nextcloud:27.1.3|image: nextcloud:31.0.8|g' stacks/apps/nextcloud.yml

# Deploy new version
echo "Deploying Nextcloud 31..."
scp stacks/apps/nextcloud.yml root@omv800:/tmp/nextcloud.yml
ssh root@omv800 "docker stack deploy -c /tmp/nextcloud.yml nextcloud"

# Wait for container
wait_for_container || exit 1
CONTAINER_ID=$(get_container_id)

# Step 5: Run upgrade
echo ""
echo "=== STEP 5: RUNNING UPGRADE ==="
echo "Running Nextcloud upgrade..."
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ upgrade"

echo "Running database maintenance..."
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ db:add-missing-indices"
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ db:convert-filecache-bigint"

echo "Scanning files..."
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ files:scan --all"
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ files:scan-app-data"

# Step 6: Verify upgrade
echo ""
echo "=== STEP 6: VERIFICATION ==="
echo "Checking new version..."
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ status"

echo "Checking for issues..."
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ check"

echo ""
echo "=== UPGRADE COMPLETED ==="
echo "✅ Nextcloud upgraded from 27.1.3 to 31.0.8"
echo "✅ Database migrated to local drive (if SQLite3)"
echo "✅ Backup created: $BACKUP_FILE"
echo ""
echo "Access at: https://nextcloud.pressmess.duckdns.org"
echo ""
echo "If you encounter issues, restore from backup:"
echo "tar -xzf $BACKUP_FILE -C /export/"
