#!/usr/bin/env bash
set -euo pipefail

REPORT_DIR="/opt/hx-ki/reports"
mkdir -p "$REPORT_DIR"

TIMESTAMP="$(date +"%Y-%m-%d_%H%M%S")"
OUTFILE="${REPORT_DIR}/HXKI_System_BirthCertificate_${TIMESTAMP}.txt"

# Hosts
NBG="ubuntu-8gb-nbg1-1"
HEL="ubuntu-16gb-hel1-1"
FSN="localhost"

# Node-Script (muss auf allen Servern liegen)
NODE_SCRIPT="/opt/hx-ki/bin/hxki_node_birth_certificate.sh"

echo "=== HXKI SYSTEM – GEBURTSURKUNDE ===" > "$OUTFILE"
echo "Erstellt: $(date)" >> "$OUTFILE"
echo >> "$OUTFILE"

make_section () {
    local HOST="$1"
    local NAME="$2"

    echo "--- Knoten: ${NAME} ---" >> "$OUTFILE"

    if [ "$HOST" = "localhost" ]; then
        NODE_FILE=$(sudo $NODE_SCRIPT | tail -n1)
        cat "$NODE_FILE" >> "$OUTFILE"
    else
        REMOTE_FILE=$(ssh "$HOST" "sudo $NODE_SCRIPT" | tail -n1)
        scp "$HOST:$REMOTE_FILE" /tmp/hxki_node.txt >/dev/null
        cat /tmp/hxki_node.txt >> "$OUTFILE"
    fi

    echo >> "$OUTFILE"
    echo >> "$OUTFILE"
}

make_section "$NBG" "NUERNBERG"
make_section "$HEL" "HELSINKI"
make_section "$FSN" "FALKENSTEIN"

echo "FERTIG."
echo "$OUTFILE"
