#!/bin/bash
# SSH-Schlüssel Management für CDN

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

show_help() {
    echo "CDN SSH Key Management"
    echo ""
    echo "Usage: $0 [OPTION]"
    echo ""
    echo "Options:"
    echo "  single     - Ein Schlüssel für alle Nodes (Standard)"
    echo "  individual - Separater Schlüssel pro Node"
    echo "  grouped    - Gruppierte Schlüssel (Primary/Secondary)"
    echo "  generate   - SSH-Schlüssel generieren"
    echo "  deploy     - Öffentliche Schlüssel zu Servern kopieren"
    echo "  help       - Diese Hilfe anzeigen"
}

generate_single_key() {
    echo "🔑 Generiere einen SSH-Schlüssel für alle CDN-Nodes..."
    
    if [ ! -f ~/.ssh/cdn_key ]; then
        ssh-keygen -t ed25519 -C "cdn-deployment" -f ~/.ssh/cdn_key -N ""
        echo "✅ Schlüssel generiert: ~/.ssh/cdn_key"
    else
        echo "ℹ️  Schlüssel existiert bereits: ~/.ssh/cdn_key"
    fi
    
    # Inventar anpassen
    sed -i 's|ansible_ssh_private_key_file: .*|ansible_ssh_private_key_file: ~/.ssh/cdn_key|' \
        "$SCRIPT_DIR/../inventories/production/hosts.yml"
    
    echo "✅ Inventar aktualisiert"
}

generate_individual_keys() {
    echo "🔑 Generiere individuelle SSH-Schlüssel..."
    
    NODES=("cdn_fra1" "cdn_ham1" "cdn_muc1" "origin1" "origin2")
    
    for node in "${NODES[@]}"; do
        if [ ! -f ~/.ssh/${node}_key ]; then
            ssh-keygen -t ed25519 -C "cdn-${node}" -f ~/.ssh/${node}_key -N ""
            echo "✅ Schlüssel generiert: ~/.ssh/${node}_key"
        else
            echo "ℹ️  Schlüssel existiert bereits: ~/.ssh/${node}_key"
        fi
    done
    
    echo "✅ Alle individuellen Schlüssel generiert"
    echo "💡 Verwende: cp inventories/production/hosts-individual-keys.yml.example inventories/production/hosts.yml"
}

generate_grouped_keys() {
    echo "🔑 Generiere gruppierte SSH-Schlüssel..."
    
    GROUPS=("origin_servers" "cdn_primary" "cdn_secondary")
    
    for group in "${GROUPS[@]}"; do
        if [ ! -f ~/.ssh/${group}_key ]; then
            ssh-keygen -t ed25519 -C "cdn-${group}" -f ~/.ssh/${group}_key -N ""
            echo "✅ Schlüssel generiert: ~/.ssh/${group}_key"
        else
            echo "ℹ️  Schlüssel existiert bereits: ~/.ssh/${group}_key"
        fi
    done
    
    echo "✅ Alle gruppierten Schlüssel generiert"
    echo "💡 Verwende: cp inventories/production/hosts-grouped-keys.yml.example inventories/production/hosts.yml"
}

deploy_keys() {
    echo "🚀 Deploye öffentliche Schlüssel zu den Servern..."
    
    # Lese IPs aus dem Inventar
    IPS=$(grep "ansible_host:" "$SCRIPT_DIR/../inventories/production/hosts.yml" | awk '{print $2}' | sort | uniq)
    
    for ip in $IPS; do
        echo "Deploying to $ip..."
        
        # Versuche verschiedene Schlüssel
        for key in ~/.ssh/*_key ~/.ssh/cdn_key ~/.ssh/id_rsa; do
            if [ -f "$key" ]; then
                echo "  Versuche Schlüssel: $key"
                if ssh-copy-id -i "${key}.pub" "root@$ip" 2>/dev/null; then
                    echo "  ✅ Erfolgreich: $key -> $ip"
                    break
                fi
            fi
        done
    done
}

case "$1" in
    "single")
        generate_single_key
        ;;
    "individual")
        generate_individual_keys
        ;;
    "grouped")
        generate_grouped_keys
        ;;
    "generate")
        echo "Welche Art von Schlüsseln?"
        echo "1) Ein Schlüssel für alle (empfohlen für Start)"
        echo "2) Individuelle Schlüssel pro Node (sicherste)"
        echo "3) Gruppierte Schlüssel (Kompromiss)"
        read -p "Wähle (1-3): " choice
        
        case $choice in
            1) generate_single_key ;;
            2) generate_individual_keys ;;
            3) generate_grouped_keys ;;
            *) echo "Ungültige Auswahl" ;;
        esac
        ;;
    "deploy")
        deploy_keys
        ;;
    "help"|*)
        show_help
        ;;
esac
