#!/bin/bash

# Activate The Events Calendar Community Events plugin
echo "🔍 Checking and activating TEC Community Events plugin..."
echo "=================================================="

source .env

# Create expect script for SSH authentication
cat > /tmp/activate_tec.expect << 'EOF'
#!/usr/bin/expect -f
set timeout 30
set password [lindex $argv 0]
set host [lindex $argv 1]
set user [lindex $argv 2]

spawn ssh -o StrictHostKeyChecking=no $user@$host

expect {
    "password:" {
        send "$password\r"
        expect "$ "
    }
    "$ " {
        # Already logged in
    }
    timeout {
        puts "Connection timeout"
        exit 1
    }
}

# Navigate to WordPress directory
send "cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html\r"
expect "$ "

# Check plugin status
send "wp plugin list | grep -i community\r"
expect "$ "

# Check if TEC Community Events exists and activate if needed
send "if wp plugin is-installed the-events-calendar-community-events 2>/dev/null; then echo 'Plugin found'; if ! wp plugin is-active the-events-calendar-community-events; then wp plugin activate the-events-calendar-community-events; echo 'Plugin activated'; else echo 'Plugin already active'; fi; else echo 'Plugin not found'; fi\r"
expect "$ "

# Also check for alternate plugin names
send "wp plugin list | grep -E '(tribe-events-community|events-community)'\r"
expect "$ "

# Clear cache after activation
send "wp cache flush\r"
expect "$ "

# Exit
send "exit\r"
expect eof
EOF

chmod +x /tmp/activate_tec.expect

# Get password from environment or prompt
if [ -z "$STAGING_SSH_PASSWORD" ]; then
    echo -n "Enter SSH password for roodev@${UPSKILL_STAGING_IP}: "
    read -s STAGING_SSH_PASSWORD
    echo
fi

# Run the expect script
/tmp/activate_tec.expect "$STAGING_SSH_PASSWORD" "$UPSKILL_STAGING_IP" "roodev"

# Clean up
rm -f /tmp/activate_tec.expect

echo ""
echo "✅ Check complete"