#!/usr/bin/env bash
# pull_remote_configs.sh — Pull nginx/WG/firewall configs from all nodes
# Run from Windows via WSL or Git Bash, or transfer to a mesh node and run there.
#
# IMPORTANT: Follows AGENTS.md hello protocol for every SSH session.
# Uses admin@gabriella key on port 9922 via WG mesh IPs.

set -euo pipefail

SSH_KEY="Y:/keys/new/gabriella"
SSH_PORT=9922
BASE_DIR="Y:/AUDIT_PACKAGE_2026-07-04/07_REMOTE_CONFIGS"

declare -A NODES=(
    [199335]="DNS:10.69.69.5:/opt/unbound/tools/resolved-sync.sh"
    [244939]="Proxy:10.69.69.3:/opt/cache-daemon/tools/networkd-diag.sh"
    [333941]="Filter:10.69.69.4:/opt/netfilter/tools/journal-compact.sh"
    [414342]="Shield:10.69.69.1:/opt/apache/engine/tools/coredump-handler.sh"
    [558201]="Origin:10.69.69.2:/opt/php-worker/tools/nginx-maint.sh"
    [669427]="Engine:10.69.69.6:/opt/apache/engine/tools/oomd-report.sh"
    [714820]="Payment:10.69.69.7:/opt/systemd-journal/tools/journal-rotate.sh"
    [869377]="Vault:10.69.69.8:/opt/stunnel/tools/cert-renew-check.sh"
)

ssh_cmd() {
    local ip="$1"; shift
    ssh -i "${SSH_KEY}" -p "${SSH_PORT}" -o StrictHostKeyChecking=no \
        -o ConnectTimeout=10 "admin@${ip}" "$@"
}

scp_cmd() {
    local ip="$1" remote="$2" local="$3"
    scp -i "${SSH_KEY}" -P "${SSH_PORT}" -o StrictHostKeyChecking=no \
        "admin@${ip}:${remote}" "${local}" 2>/dev/null || true
}

for nid in "${!NODES[@]}"; do
    IFS=':' read -r name ip hello_tool <<< "${NODES[$nid]}"
    dest="${BASE_DIR}/${name}_${nid}"
    mkdir -p "${dest}/wireguard" "${dest}/nginx" "${dest}/firewall"

    echo "=== ${name} (${nid}) @ ${ip} ==="

    # Hello check-in + pull configs in one SSH session
    ssh_cmd "${ip}" "
        # Hello check-in (AGENTS.md compliance)
        sudo ${hello_tool} check-in 'maintenance' 'node' 3600 2>/dev/null || true

        # Create agent_rotating token
        sudo touch /run/se/state/agent_rotating

        echo '--- WIREGUARD ---'
        # WireGuard configs (strip private keys for safety)
        for conf in /etc/wireguard/*.conf; do
            if [ -f \"\$conf\" ]; then
                basename=\$(basename \"\$conf\")
                echo \"FILE:\${basename}\"
                sudo grep -v 'PrivateKey' \"\$conf\" || true
                echo '---END---'
            fi
        done

        echo '--- NGINX ---'
        # Nginx configs (if nginx is installed)
        if command -v nginx &>/dev/null; then
            echo 'FILE:nginx.conf'
            sudo cat /etc/nginx/nginx.conf 2>/dev/null || true
            echo '---END---'
            for conf in /etc/nginx/conf.d/*.conf /etc/nginx/sites-enabled/*; do
                if [ -f \"\$conf\" ]; then
                    echo \"FILE:\$(basename \$conf)\"
                    sudo cat \"\$conf\" 2>/dev/null || true
                    echo '---END---'
                fi
            done
        else
            echo 'NGINX_NOT_INSTALLED'
        fi

        echo '--- FIREWALL ---'
        # Firewall state
        if command -v firewall-cmd &>/dev/null; then
            echo 'TYPE:firewalld'
            echo 'DEFAULT_ZONE:'
            sudo firewall-cmd --get-default-zone 2>/dev/null || true
            echo 'ZONES:'
            for zone in \$(sudo firewall-cmd --get-zones 2>/dev/null); do
                echo \"ZONE:\${zone}\"
                sudo firewall-cmd --zone=\"\${zone}\" --list-all 2>/dev/null || true
            done
            echo 'RICH_RULES:'
            sudo firewall-cmd --list-rich-rules 2>/dev/null || true
        elif command -v ufw &>/dev/null; then
            echo 'TYPE:ufw'
            sudo ufw status verbose 2>/dev/null || true
        fi

        echo '--- MARIADB ---'
        if command -v mysql &>/dev/null || command -v mariadb &>/dev/null; then
            echo 'MARIADB_INSTALLED'
            systemctl is-active mariadb 2>/dev/null || systemctl is-active mysql 2>/dev/null || echo 'NOT_RUNNING'
            sudo mysql -e 'SHOW DATABASES;' 2>/dev/null || echo 'CANNOT_CONNECT'
        else
            echo 'MARIADB_NOT_INSTALLED'
        fi

        # Cleanup
        sudo rm -f /run/se/state/agent_rotating

        # Goodbye
        sudo ${hello_tool} goodbye 2>/dev/null || true
    " > "${dest}/raw_pull_output.txt" 2>&1 || echo "FAILED to connect to ${name}"

    echo "    Saved to ${dest}/raw_pull_output.txt"
done

echo ""
echo "=== Pull complete ==="
echo "Raw output in: ${BASE_DIR}/*/raw_pull_output.txt"
echo "Parse and split files as needed for audit submission."
