#!/bin/bash

# Fix-Skript für Webserver-Konflikte mit parallelen Symfony-Projekten
# Auf dem Webserver ausführen: sudo bash fix_webserver_conflicts.sh

PROJECT_DIR="/var/www/html/fleet_monitoring"
WEB_USER="www-data"

echo "=== Fix für Webserver-Konflikte ==="
echo "Projekt-Verzeichnis: $PROJECT_DIR"
echo ""

cd "$PROJECT_DIR" || exit 1

# 1. Cache komplett leeren
echo "1. Leere Cache..."
rm -rf var/cache/prod/*
rm -rf var/cache/dev/*
php bin/console cache:clear --env=prod --no-warmup 2>/dev/null || true
php bin/console cache:clear --env=dev --no-warmup 2>/dev/null || true

# 2. Berechtigungen setzen
echo "2. Setze Berechtigungen..."
chown -R $WEB_USER:$WEB_USER var
chmod -R 775 var

# 3. Prüfe Konfiguration
echo "3. Prüfe Konfiguration..."
if grep -q "cache.adapter.apcu" config/packages/doctrine.yaml; then
    echo "   ⚠️  WARNUNG: APCu wird noch verwendet in doctrine.yaml!"
fi

if grep -q "^framework:" config/packages/mailer.yaml && ! grep -q "^#" config/packages/mailer.yaml | head -1; then
    echo "   ⚠️  WARNUNG: Mailer-Konfiguration ist noch aktiv!"
fi

if grep -q "^framework:" config/packages/messenger.yaml && ! grep -q "^#" config/packages/messenger.yaml | head -1; then
    echo "   ⚠️  WARNUNG: Messenger-Konfiguration ist noch aktiv!"
fi

# 4. Prüfe auf parallele Projekte
echo "4. Prüfe auf parallele Projekte..."
PARALLEL_PROJECTS=$(find /var/www/html -maxdepth 1 -type d -name "*" ! -name "html" ! -name "." 2>/dev/null | wc -l)
if [ "$PARALLEL_PROJECTS" -gt 1 ]; then
    echo "   ⚠️  WARNUNG: $PARALLEL_PROJECTS Projekte gefunden in /var/www/html"
    echo "   Stelle sicher, dass jedes Projekt einen eindeutigen Cache-Prefix hat!"
fi

# 5. PHP-FPM/Apache neu starten
echo "5. Starte PHP-FPM neu..."
if systemctl is-active --quiet php8.2-fpm; then
    systemctl restart php8.2-fpm
    echo "   ✓ PHP-FPM neu gestartet"
elif systemctl is-active --quiet php8.1-fpm; then
    systemctl restart php8.1-fpm
    echo "   ✓ PHP-FPM neu gestartet"
elif systemctl is-active --quiet apache2; then
    systemctl restart apache2
    echo "   ✓ Apache neu gestartet"
else
    echo "   ⚠️  Kein PHP-FPM oder Apache gefunden"
fi

echo ""
echo "=== Fertig! ==="
echo "Bitte teste die Datalogger-API jetzt."
