#!/bin/bash

# Shopware 6 Export Script - Alle Product Exports ausführen

# Konfiguration
SHOPWARE_ROOT="/var/www/we8upmb/htdocs/lb_staging"
LOG_FILE="/var/www/we8upmb/htdocs/lb_staging/var/log/shopware_exports.log"

# Datenbank Konfiguration
DB_HOST="localhost"
DB_USER="12-production"
DB_PASS="O4NSh8E{^R_15U=T"
DB_NAME="12-production"

# Slack Webhook Konfiguration
SLACK_WEBHOOK_URL="https://hooks.slack.com/services/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"
SLACK_ENABLED=true  # Auf false setzen um Slack zu deaktivieren

# Export Konfiguration
USE_FORCE=true  # Auf false setzen um --force zu deaktivieren

# Logging
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Slack Benachrichtigung senden
send_slack_notification() {
    local status="$1"
    local file_name="$2"
    local duration="$3"
    local current="$4"
    local total="$5"
    
    if [ "$SLACK_ENABLED" != "true" ]; then
        return 0
    fi
    
    # Farbe und Emoji basierend auf Status
    if [ "$status" = "SUCCESS" ]; then
        local color="good"
        local emoji=":white_check_mark:"
    else
        local color="danger" 
        local emoji=":x:"
    fi
    
    # Slack Payload erstellen
    local payload=$(cat <<EOF
{
    "attachments": [
        {
            "color": "$color",
            "fields": [
                {
                    "title": "${emoji} Export $status",
                    "value": "$file_name",
                    "short": true
                },
                {
                    "title": "Fortschritt",
                    "value": "$current/$total",
                    "short": true
                },
                {
                    "title": "Dauer",
                    "value": "${duration}s",
                    "short": true
                }
            ],
            "footer": "Shopware Export Script",
            "ts": $(date +%s)
        }
    ]
}
EOF
)
    
    # An Slack senden
    curl -s -X POST -H 'Content-type: application/json' \
        --data "$payload" \
        "$SLACK_WEBHOOK_URL" > /dev/null 2>&1
}

# Alle Product Exports aus der Datenbank holen
get_product_exports() {
    mariadb -h "$DB_HOST" -u "$DB_USER" ${DB_PASS:+-p"$DB_PASS"} "$DB_NAME" -s -N -e "
        SELECT CONCAT(LOWER(HEX(pe.storefront_sales_channel_id)), ':', LOWER(HEX(pe.id)), ':', pe.file_name)
        FROM product_export pe
        JOIN sales_channel sc ON pe.sales_channel_id = sc.id
        WHERE sc.active = 1 and pe.generate_by_cronjob = 0
        ORDER BY pe.file_name
    " 2>/dev/null
}

# Hauptprogramm
cd "$SHOPWARE_ROOT" || {
    log "FEHLER: Kann nicht zu $SHOPWARE_ROOT wechseln"
    exit 1
}

START_SCRIPT=$(date +%s)
SCRIPT_SESSION="SCRIPT_$$_$(date +%s)"  # Eindeutige Session-ID mit PID
log "=== Shopware Export Script gestartet ($SCRIPT_SESSION) ==="

# Product Exports laden
EXPORTS=$(get_product_exports)

# Prüfen ob Exports gefunden wurden
if [ -z "$EXPORTS" ]; then
    log "WARNUNG: Keine Product Exports gefunden"
    exit 0
fi

EXPORT_COUNT=$(echo "$EXPORTS" | wc -l)
log "Gefunden: $EXPORT_COUNT Product Exports"

# Zähler initialisieren
SUCCESS_COUNT=0
FAILED_COUNT=0
CURRENT=0

# WICHTIG: Process Substitution verwenden statt Pipe um Subshell zu vermeiden
while read -r export_line; do
    if [ -n "$export_line" ]; then
        CURRENT=$((CURRENT + 1))
        
        # Export-Daten extrahieren
        storefront_channel=$(echo "$export_line" | cut -d':' -f1)
        export_id=$(echo "$export_line" | cut -d':' -f2)
        file_name=$(echo "$export_line" | cut -d':' -f3)
        
        log "[$CURRENT/$EXPORT_COUNT] Export: $file_name"
        
        # Force-Flag setzen falls aktiviert
        FORCE_FLAG=""
        if [ "$USE_FORCE" = "true" ]; then
            FORCE_FLAG="--force"
        fi
        
        # Export ausführen mit Zeitmessung
        START_TIME=$(date +%s)
        
        # Temporäre Datei für Fehlerausgabe
        TEMP_LOG=$(mktemp)
        
        if timeout 3600 php -dmemory_limit=2G bin/console product-export:generate "$storefront_channel" "$export_id" $FORCE_FLAG >> "$LOG_FILE" 2>"$TEMP_LOG"; then
            END_TIME=$(date +%s)
            DURATION=$((END_TIME - START_TIME))
            SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
            log "✅ SUCCESS: $file_name (${DURATION}s) [$SCRIPT_SESSION]"
            # Erfolgreiche Slack-Benachrichtigung ist auskommentiert
            #send_slack_notification "SUCCESS" "$file_name" "$DURATION" "$CURRENT" "$EXPORT_COUNT"
        else
            END_TIME=$(date +%s)
            DURATION=$((END_TIME - START_TIME))
            FAILED_COUNT=$((FAILED_COUNT + 1))
            
            # Fehlermeldung extrahieren und bereinigen
            ERROR_MSG=""
            if [ -s "$TEMP_LOG" ]; then
                # Erste aussagekräftige Zeile als Fehlermeldung verwenden
                ERROR_MSG=$(head -n 3 "$TEMP_LOG" | grep -v "^$" | head -n 1 | sed 's/"/\\"/g' | cut -c1-200)
                log "❌ FAILED: $file_name (${DURATION}s) - Fehler: $ERROR_MSG"
                cat "$TEMP_LOG" >> "$LOG_FILE"
            else
                ERROR_MSG="Timeout oder unbekannter Fehler"
                log "❌ FAILED: $file_name (${DURATION}s) - $ERROR_MSG"
            fi
            
            send_slack_notification "FAILED" "$file_name" "$DURATION" "$CURRENT" "$EXPORT_COUNT" "$ERROR_MSG"
        fi
        
        # Temporäre Datei löschen
        rm -f "$TEMP_LOG"
    fi
done < <(echo "$EXPORTS")  # Process Substitution statt Pipe!

# Zusammenfassung
TOTAL_TIME=$(($(date +%s) - START_SCRIPT))
log "=== Fertig ($SCRIPT_SESSION) ==="
log "Erfolgreich: $SUCCESS_COUNT | Fehlgeschlagen: $FAILED_COUNT | Gesamtdauer: ${TOTAL_TIME}s"

# Slack Summary senden
if [ "$SLACK_ENABLED" = "true" ]; then
    if [ "$FAILED_COUNT" -eq 0 ]; then
        COLOR="good"
        EMOJI=":tada:"
        STATUS_TEXT="Alle Exports erfolgreich!"
    else
        COLOR="warning"
        EMOJI=":warning:"
        STATUS_TEXT="$FAILED_COUNT von $EXPORT_COUNT Exports fehlgeschlagen"
    fi
    
    SUMMARY_PAYLOAD=$(cat <<EOF
{
    "attachments": [
        {
            "color": "$COLOR",
            "title": "${EMOJI} Shopware Export Summary",
            "fields": [
                {
                    "title": "Status",
                    "value": "$STATUS_TEXT",
                    "short": false
                },
                {
                    "title": "Erfolgreich",
                    "value": "$SUCCESS_COUNT",
                    "short": true
                },
                {
                    "title": "Fehlgeschlagen", 
                    "value": "$FAILED_COUNT",
                    "short": true
                },
                {
                    "title": "Gesamtdauer",
                    "value": "${TOTAL_TIME}s",
                    "short": true
                }
            ],
            "footer": "Shopware Export Script - Zusammenfassung",
            "ts": $(date +%s)
        }
    ]
}
EOF
)
    
    curl -s -X POST -H 'Content-type: application/json' \
        --data "$SUMMARY_PAYLOAD" \
        "$SLACK_WEBHOOK_URL" > /dev/null 2>&1
fi