#!/usr/bin/env bash
# Phase 7.x — Mac-Variante: Connect-Info Collector
# Doppelklick im Finder oeffnet diese Datei im Terminal (chmod +x notwendig).
# Sammelt Hostname/IP/User/OS, postet an https://bridge.xxbillion.ai/submit.

set -u

WIZARD_URL="${WIZARD_URL:-https://bridge.xxbillion.ai/submit}"
DEVICE_LABEL="${DEVICE_LABEL:-mac-workstation-$(hostname -s)}"

echo "==============================================="
echo "  Phase 7.x Connect-Info Collector (Mac)"
echo "==============================================="
echo

BODY=$(cat <<EOF
=== mac connect-info ===
device_label : ${DEVICE_LABEL}
hostname     : $(hostname -f 2>/dev/null || hostname)
short_host   : $(hostname -s)
user         : $(id -un)
uid          : $(id -u)
os           : $(uname -s) $(uname -r)
arch         : $(uname -m)
sw_vers      : $(sw_vers 2>/dev/null | tr '\n' ' ' | sed 's/  */ /g')
uptime       : $(uptime)

--- network ---
ifconfig (active interfaces):
$(ifconfig 2>/dev/null | grep -E "^[a-z0-9]+|inet " | grep -A1 "flags=.*RUNNING" | grep "inet " | head -10)

public_ip4   : $(curl -s --max-time 4 https://api.ipify.org 2>/dev/null || echo "?")
public_ip6   : $(curl -s --max-time 4 https://api6.ipify.org 2>/dev/null || echo "?")
dns_resolver : $(scutil --dns 2>/dev/null | grep "nameserver\[" | head -3 | tr '\n' ' ')

--- ssh ---
ssh_version  : $(ssh -V 2>&1)
local_pubkey :
$(cat ~/.ssh/id_ed25519.pub 2>/dev/null || cat ~/.ssh/id_rsa.pub 2>/dev/null || echo "(kein lokaler key)")

--- timestamp ---
recorded_at  : $(date -u +%Y-%m-%dT%H:%M:%SZ)
EOF
)

echo "$BODY"
echo
echo "==============================================="
echo "  Sende an ${WIZARD_URL} ..."
echo "==============================================="

HTTP=$(curl -s -o /tmp/phase7x_submit_response.json -w "%{http_code}" \
  -X POST \
  -H "Content-Type: text/plain; charset=utf-8" \
  -H "User-Agent: phase7x-mac-collector" \
  --data-binary "$BODY" \
  --max-time 10 \
  "$WIZARD_URL")

echo
if [ "$HTTP" = "200" ]; then
    echo "✓ OK (HTTP $HTTP)"
    cat /tmp/phase7x_submit_response.json 2>/dev/null
    echo
    # Pasteboard fallback
    echo "$BODY" | pbcopy 2>/dev/null && echo "✓ Output auch in Zwischenablage."
else
    echo "✗ FEHLER (HTTP $HTTP)"
    cat /tmp/phase7x_submit_response.json 2>/dev/null
fi
echo
echo "Fenster bleibt offen — Enter zum Schliessen."
read -r _
