#!/bin/bash
# Fix ionCube loader for PHP-FPM 7.4 (billing site)
# Run with: sudo bash fix-ioncube-billing.sh

echo "=== Fixing ionCube Loader for PHP-FPM 7.4 ==="
echo ""

# Check if loader file exists
LOADER_FILE="/usr/lib/php/20190902/ioncube_loader_lin_7.4.so"
if [ ! -f "$LOADER_FILE" ]; then
    echo "❌ Loader file not found: $LOADER_FILE"
    echo "Please download from: https://downloads.ioncube.com/loader_downloads/"
    exit 1
fi

echo "✓ Loader file exists: $LOADER_FILE"
echo ""

# Ensure config file exists
CONFIG_FILE="/etc/php/7.4/fpm/conf.d/00-ioncube.ini"
MODS_FILE="/etc/php/7.4/mods-available/00-ioncube.ini"

echo "1. Checking configuration..."
if [ ! -f "$MODS_FILE" ]; then
    echo "Creating mods-available file..."
    echo "zend_extension = $LOADER_FILE" | sudo tee "$MODS_FILE" > /dev/null
    echo "✓ Created $MODS_FILE"
fi

if [ ! -L "$CONFIG_FILE" ] && [ ! -f "$CONFIG_FILE" ]; then
    echo "Creating symlink..."
    sudo ln -s "$MODS_FILE" "$CONFIG_FILE"
    echo "✓ Created symlink"
elif [ -f "$CONFIG_FILE" ]; then
    echo "✓ Config file exists: $CONFIG_FILE"
    cat "$CONFIG_FILE"
fi

echo ""

# Verify the configuration
echo "2. Verifying configuration..."
if grep -q "ioncube_loader_lin_7.4.so" "$CONFIG_FILE" 2>/dev/null || grep -q "ioncube_loader_lin_7.4.so" "$MODS_FILE" 2>/dev/null; then
    echo "✓ Configuration looks correct"
else
    echo "⚠️  Configuration might be incorrect"
    echo "Expected: zend_extension = $LOADER_FILE"
fi

echo ""

# Restart PHP-FPM
echo "3. Restarting PHP-FPM 7.4..."
sudo systemctl restart php7.4-fpm
sleep 2

if sudo systemctl is-active --quiet php7.4-fpm; then
    echo "✓ PHP-FPM 7.4 restarted successfully"
else
    echo "❌ PHP-FPM 7.4 failed to restart"
    sudo systemctl status php7.4-fpm --no-pager | head -10
    exit 1
fi

echo ""

# Test if ionCube is loaded
echo "4. Testing ionCube loader..."
if php7.4-fpm -m 2>/dev/null | grep -qi ioncube; then
    echo "✅ ionCube Loader is now loaded in PHP-FPM 7.4!"
else
    echo "⚠️  ionCube still not loaded"
    echo ""
    echo "Checking PHP-FPM error log..."
    sudo tail -5 /var/log/php7.4-fpm.log 2>/dev/null || echo "No error log found"
    echo ""
    echo "Try checking manually:"
    echo "  sudo -u www-data php7.4-fpm -m | grep ioncube"
fi

echo ""
echo "5. Testing billing site..."
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://billing.friendlytv.site/ 2>&1)
echo "   https://billing.friendlytv.site/: HTTP $HTTP_CODE"

if [ "$HTTP_CODE" = "200" ]; then
    echo ""
    echo "✅ SUCCESS! Billing site should be working now!"
else
    echo ""
    echo "⚠️  Still getting $HTTP_CODE"
    echo "   Check Apache error log: sudo tail -10 /var/log/apache2/error.log"
fi

