#!/bin/bash

# Fix Spreed Database Migration Script
# Fixes the "inCall" column type issue in oc_talk_participants table
# Created: $(date)

set -e

echo "=== Fixing Spreed Database Migration Issue ==="
echo ""

# Get container ID
echo "Getting Nextcloud container ID..."
CONTAINER_ID=$(ssh root@omv800 "docker ps -q -f name=nextcloud" | head -1)
if [ -z "$CONTAINER_ID" ]; then
    echo "❌ Nextcloud container not found"
    exit 1
fi
echo "✅ Container found: $CONTAINER_ID"

# Check if Nextcloud is in maintenance mode
echo ""
echo "Checking maintenance mode status..."
MAINTENANCE_STATUS=$(ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ status" | grep "maintenance" | cut -d' ' -f3)
echo "Maintenance mode: $MAINTENANCE_STATUS"

if [ "$MAINTENANCE_STATUS" = "true" ]; then
    echo "Disabling maintenance mode..."
    ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ maintenance:mode --off"
    echo "✅ Maintenance mode disabled"
fi

# Try to fix the database issue by running repair commands
echo ""
echo "Running database repair commands..."

echo "1. Adding missing indices..."
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ db:add-missing-indices"

echo "2. Converting filecache to bigint..."
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ db:convert-filecache-bigint"

echo "3. Running database check..."
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ check"

# Try to manually fix the Spreed database issue
echo ""
echo "Attempting to fix Spreed database schema..."

# Check if the problematic table exists and fix the column type
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php -r '
\$db = new SQLite3(\"/var/www/html/data/owncloud.db\");
\$db->enableExceptions(true);

try {
    // Check if the table exists
    \$result = \$db->query(\"SELECT name FROM sqlite_master WHERE type='table' AND name='oc_talk_participants'\");
    if (\$result->fetchArray()) {
        echo \"Table oc_talk_participants exists\n\";
        
        // Check the current schema
        \$schema = \$db->query(\"PRAGMA table_info(oc_talk_participants)\");
        \$inCallColumn = null;
        while (\$row = \$schema->fetchArray(SQLITE3_ASSOC)) {
            if (\$row[\"name\"] == \"inCall\") {
                \$inCallColumn = \$row;
                break;
            }
        }
        
        if (\$inCallColumn) {
            echo \"inCall column found: \" . \$inCallColumn[\"type\"] . \" (notnull: \" . \$inCallColumn[\"notnull\"] . \")\n\";
            
            // If the column is BOOLEAN and NOT NULL, we need to fix it
            if (strpos(strtolower(\$inCallColumn[\"type\"]), \"bool\") !== false && \$inCallColumn[\"notnull\"] == 1) {
                echo \"Fixing inCall column...\n\";
                
                // Create a temporary table with the correct schema
                \$db->exec(\"CREATE TABLE oc_talk_participants_temp AS SELECT * FROM oc_talk_participants\");
                
                // Drop the original table
                \$db->exec(\"DROP TABLE oc_talk_participants\");
                
                // Recreate the table with the correct schema
                \$db->exec(\"CREATE TABLE oc_talk_participants AS SELECT * FROM oc_talk_participants_temp\");
                
                // Drop the temporary table
                \$db->exec(\"DROP TABLE oc_talk_participants_temp\");
                
                echo \"Table schema fixed successfully\n\";
            } else {
                echo \"inCall column is already correct\n\";
            }
        } else {
            echo \"inCall column not found\n\";
        }
    } else {
        echo \"Table oc_talk_participants does not exist\n\";
    }
} catch (Exception \$e) {
    echo \"Error: \" . \$e->getMessage() . \"\n\";
}
\$db->close();
'"

# Try to run the upgrade again
echo ""
echo "Running upgrade command again..."
ssh root@omv800 "docker exec -u 33 $CONTAINER_ID php /var/www/html/occ upgrade"

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

echo ""
echo "=== Spreed Database Fix Complete ==="
echo "If the issue persists, you may need to:"
echo "1. Disable the Spreed app temporarily"
echo "2. Run the upgrade again"
echo "3. Re-enable the Spreed app"
echo ""
echo "To disable Spreed: docker exec -u 33 $CONTAINER_ID php /var/www/html/occ app:disable spreed"
echo "To enable Spreed: docker exec -u 33 $CONTAINER_ID php /var/www/html/occ app:enable spreed"
