#!/bin/bash

# Скрипт для фиксации оставшихся проблем
LOG_FILE="/tmp/fix_remaining_$(date +%Y%m%d_%H%M%S).log"
exec > >(tee -a "$LOG_FILE") 2>&1

echo "=== Fixing remaining Apache issues ==="

# 1. Backup current config
sudo cp /etc/httpd/conf.d/pinkcookietv.conf /etc/httpd/conf.d/pinkcookietv.conf.backup

# 2. Fix .htaccess access for /ilove directory
echo "Fixing .htaccess access for /ilove..."
sudo tee -a /etc/httpd/conf.d/pinkcookietv.conf << 'EOF'

# Fix for /ilove directory .htaccess access
<Directory "/web/pinkcookietv.ru/www/ilove">
    AllowOverride All
    Require all granted
    Options -Indexes +FollowSymLinks
    
    # Security headers
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "SAMEORIGIN"
</Directory>
EOF

# 3. Fix CGI errors (optional - block access to cgi-bin)
echo "Blocking access to /cgi-bin to stop CGI errors..."
sudo tee /etc/httpd/conf.d/block-cgi.conf << 'EOF'
# Block access to cgi-bin to stop missing_handler.pl errors
<Directory "/var/www/cgi-bin">
    Require all denied
</Directory>

<Location "/cgi-bin">
    Require all denied
</Location>
EOF

# 4. Check admin.php file
echo "Checking admin.php..."
if [ -f "/web/pinkcookietv.ru/www/ilove/admin.php" ]; then
    echo "admin.php exists, checking permissions..."
    sudo chmod 644 /web/pinkcookietv.ru/www/ilove/admin.php
    sudo chown apache:apache /web/pinkcookietv.ru/www/ilove/admin.php
else
    echo "WARNING: admin.php not found at /web/pinkcookietv.ru/www/ilove/admin.php"
    echo "Creating placeholder (optional)..."
    sudo tee /web/pinkcookietv.ru/www/ilove/admin.php << 'PHP'
<?php
// Admin placeholder
header("HTTP/1.0 404 Not Found");
echo "Admin interface not available";
?>
PHP
    sudo chmod 644 /web/pinkcookietv.ru/www/ilove/admin.php
    sudo chown apache:apache /web/pinkcookietv.ru/www/ilove/admin.php
fi

# 5. Test configuration
echo "Testing Apache configuration..."
sudo apachectl configtest

# 6. Reload Apache
echo "Reloading Apache..."
sudo systemctl reload httpd

# 7. Test fixes
echo "Testing fixes..."
echo "1. Testing .htaccess access..."
curl -s -o /dev/null -w "HTTP Status: %{http_code}\n" http://localhost/ilove/

echo "2. Testing admin.php..."
curl -s -o /dev/null -w "admin.php Status: %{http_code}\n" http://localhost/ilove/admin.php

echo "3. Checking for recent errors..."
sudo tail -5 /var/log/httpd/error_log

echo "=== Fix complete! ==="
echo "Log file: $LOG_FILE"
