#!/bin/bash
# Einfaches CDN Monitoring für {{ inventory_hostname }}

LOG_FILE="/var/log/nginx/cdn-monitor.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
CDN_DOMAIN="{{ cdn_domain }}"

# Health Check
health_check() {
    local response=$(curl -s -o /dev/null -w "%{http_code}" "https://$CDN_DOMAIN/health")
    
    if [ "$response" = "200" ]; then
        echo "[$TIMESTAMP] ✅ Health check OK" >> $LOG_FILE
        return 0
    else
        echo "[$TIMESTAMP] ❌ Health check FAILED (HTTP $response)" >> $LOG_FILE
        return 1
    fi
}

# Nginx-Statistiken
nginx_stats() {
    local stats=$(curl -s http://127.0.0.1/nginx_status 2>/dev/null)
    if [ $? -eq 0 ]; then
        local active_conn=$(echo "$stats" | grep "Active connections" | awk '{print $3}')
        local total_requests=$(echo "$stats" | grep "server accepts" | awk '{print $3}')
        echo "[$TIMESTAMP] 📊 Active: $active_conn, Total: $total_requests" >> $LOG_FILE
    fi
}

# Cache-Größe prüfen
cache_check() {
    local cache_size=$(du -sh /var/cache/nginx/ 2>/dev/null | cut -f1)
    local cache_files=$(find /var/cache/nginx/ -type f 2>/dev/null | wc -l)
    echo "[$TIMESTAMP] 💾 Cache: $cache_size ($cache_files files)" >> $LOG_FILE
}

# System-Ressourcen
system_check() {
    local load=$(uptime | awk -F'load average:' '{print $2}' | awk -F',' '{print $1}' | tr -d ' ')
    local memory=$(free | grep Mem | awk '{printf "%.1f", $3/$2 * 100.0}')
    local disk=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
    
    echo "[$TIMESTAMP] 🖥️  Load: $load, Memory: ${memory}%, Disk: ${disk}%" >> $LOG_FILE
    
    # Warnungen bei hoher Auslastung
    if (( $(echo "$load > 5.0" | bc -l 2>/dev/null || echo 0) )); then
        echo "[$TIMESTAMP] ⚠️  HIGH LOAD WARNING: $load" >> $LOG_FILE
    fi
    
    if (( $(echo "$memory > 90.0" | bc -l 2>/dev/null || echo 0) )); then
        echo "[$TIMESTAMP] ⚠️  HIGH MEMORY WARNING: ${memory}%" >> $LOG_FILE
    fi
    
    if [ "$disk" -gt 85 ]; then
        echo "[$TIMESTAMP] ⚠️  HIGH DISK USAGE WARNING: ${disk}%" >> $LOG_FILE
    fi
}

# Hauptausführung
main() {
    health_check
    nginx_stats
    cache_check
    system_check
    
    # Log-Datei begrenzen (nur letzte 1000 Zeilen behalten)
    tail -n 1000 $LOG_FILE > ${LOG_FILE}.tmp && mv ${LOG_FILE}.tmp $LOG_FILE
}

main
