#!/bin/bash

# Quick fix for nnfss2.com - foolproof version

set -e

echo "=== Fixing nnfss2.com 404 redirect ==="
echo ""

# Enable mod_rewrite
echo "Step 1: Enabling mod_rewrite..."
a2enmod rewrite 2>/dev/null || echo "Already enabled"

# Find the actual DocumentRoot
echo "Step 2: Finding DocumentRoot..."
VHOST="/etc/apache2/sites-available/nnfss2.com.conf"

if [ ! -f "$VHOST" ]; then
    echo "ERROR: $VHOST not found"
    exit 1
fi

# Extract DocumentRoot properly (handle multiple formats)
PUBLIC_HTML=$(grep -i "^\s*DocumentRoot" "$VHOST" | sed 's/DocumentRoot\s*//' | tr -d '"' | tr -d "'" | head -1)

if [ -z "$PUBLIC_HTML" ]; then
    echo "ERROR: Could not find DocumentRoot in $VHOST"
    echo "Please check the file manually"
    exit 1
fi

echo "Found DocumentRoot: $PUBLIC_HTML"

# Verify directory exists
if [ ! -d "$PUBLIC_HTML" ]; then
    echo "ERROR: Directory does not exist: $PUBLIC_HTML"
    echo "Creating it..."
    mkdir -p "$PUBLIC_HTML"
fi

# Step 3: Fix AllowOverride in virtual host
echo "Step 3: Fixing AllowOverride in virtual host..."
cp "$VHOST" "${VHOST}.backup-$(date +%Y%m%d-%H%M%S)"

# Check if Directory block exists for this path
if grep -q "<Directory.*$PUBLIC_HTML" "$VHOST"; then
    # Update existing
    sed -i "/<Directory.*$PUBLIC_HTML/,/<\/Directory>/s/AllowOverride.*/        AllowOverride All/" "$VHOST"
    echo "Updated existing Directory block"
elif grep -q "<Directory" "$VHOST"; then
    # Update any Directory block
    sed -i "s/AllowOverride.*/AllowOverride All/" "$VHOST"
    echo "Updated Directory block"
else
    # Add new Directory block before </VirtualHost>
    sed -i "/<\/VirtualHost>/i\    <Directory $PUBLIC_HTML>\n        Options -Indexes +FollowSymLinks\n        AllowOverride All\n        Require all granted\n    </Directory>\n" "$VHOST"
    echo "Added new Directory block"
fi

# Step 4: Create .htaccess
echo "Step 4: Creating .htaccess..."
HTACCESS="$PUBLIC_HTML/.htaccess"

if [ -f "$HTACCESS" ]; then
    cp "$HTACCESS" "${HTACCESS}.backup-$(date +%Y%m%d-%H%M%S)"
    echo "Backed up existing .htaccess"
fi

cat > "$HTACCESS" << 'EOF'
ErrorDocument 404 /
RewriteEngine On
RewriteBase /
Options -Indexes +FollowSymLinks
AddDefaultCharset UTF-8
EOF

chown www-data:www-data "$HTACCESS"
chmod 644 "$HTACCESS"
echo "Created: $HTACCESS"

# Step 5: Test and reload
echo "Step 5: Testing configuration..."
if apache2ctl configtest 2>&1 | grep -q "Syntax OK"; then
    echo "✓ Configuration OK"
    echo "Reloading Apache..."
    systemctl reload apache2
    echo "✓ Apache reloaded"
else
    echo "ERROR: Configuration test failed"
    apache2ctl configtest
    exit 1
fi

# Step 6: Test the fix
echo ""
echo "=== Testing 404 redirect ==="
sleep 2

HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://nnfss2.com/test-$(date +%s) 2>/dev/null || echo "000")

if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "301" ] || [ "$HTTP_CODE" = "302" ]; then
    echo "✓✓✓ SUCCESS! Got HTTP $HTTP_CODE ✓✓✓"
    echo ""
    echo "Test it: https://nnfss2.com/blah"
    echo "Should redirect to: https://nnfss2.com/"
else
    echo "Got HTTP $HTTP_CODE"
    echo ""
    echo "If still showing 404, check:"
    echo "1. View vhost: cat $VHOST | grep -A5 Directory"
    echo "2. View .htaccess: cat $HTACCESS"
    echo "3. Check logs: tail /var/log/apache2/error.log"
fi

echo ""
echo "=== Summary ==="
echo "Virtual host: $VHOST (backed up)"
echo "Document root: $PUBLIC_HTML"
echo ".htaccess: $HTACCESS (backed up)"
echo ""

exit 0
