#!/bin/bash

echo "=== YourPart Quick CORS Fix ==="

# 1. Apache headers-Modul aktivieren
echo "Aktiviere Apache headers-Modul..."
sudo a2enmod headers

# 2. Port in HTTP-Konfiguration korrigieren
echo "Korrigiere Port in HTTP-Konfiguration..."
sudo sed -i 's/2020/3001/g' /etc/apache2/sites-available/yourpart-http.conf

# 3. Port in HTTPS-Konfiguration korrigieren
echo "Korrigiere Port in HTTPS-Konfiguration..."
sudo sed -i 's/2020/3001/g' /etc/apache2/sites-available/yourpart-https.conf

# 4. CORS-Header zu HTTPS-Konfiguration hinzufügen
echo "Füge CORS-Header hinzu..."
sudo sed -i '/<Directory "\/opt\/yourpart\/frontend\/dist">/a\
\
    # CORS-Header für alle Requests\
    Header always set Access-Control-Allow-Origin "*"\
    Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"\
    Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization, userId, authCode"\
    Header always set Access-Control-Allow-Credentials "true"\
' /etc/apache2/sites-available/yourpart-https.conf

# 5. CORS-Header für API-Requests hinzufügen
echo "Füge API CORS-Header hinzu..."
sudo sed -i '/ProxyPassReverse "\/socket.io\/"/a\
\
    # CORS-Header für API-Requests\
    <Location "\/api\/">\
        Header always set Access-Control-Allow-Origin "*"\
        Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"\
        Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization, userId, authCode"\
        Header always set Access-Control-Allow-Credentials "true"\
        \
        # OPTIONS-Requests behandeln\
        RewriteEngine On\
        RewriteCond %{REQUEST_METHOD} OPTIONS\
        RewriteRule ^(.*)$ $1 [R=200,L]\
    </Location>\
' /etc/apache2/sites-available/yourpart-https.conf

# 6. Apache neu laden
echo "Lade Apache neu..."
sudo systemctl reload apache2

echo ""
echo "=== Quick CORS Fix abgeschlossen! ==="
echo "✅ Port korrigiert (3001)"
echo "✅ CORS-Header hinzugefügt"
echo "✅ Apache neu geladen"
echo ""
echo "Testen Sie jetzt die Anwendung!"
