#!/usr/bin/env bash
# host-inventory capture script.
# Foreground-only. Prints a Markdown report + JSON excerpt to stdout.
# Drop any section that errors — partial output is preferred over a failed run.

set -u  # NOTE: deliberately NOT `set -e`; we want partial output on error.
LC_ALL=C

section() { printf "\n=== %s ===\n" "$1"; }
have()     { command -v "$1" >/dev/null 2>&1; }

section "IDENTITY"
uname -a
[ -r /etc/os-release ] && head -5 /etc/os-release
hostname
uptime
whoami
date

section "HARDWARE"
have lscpu && lscpu | grep -E "Model name|CPU\(s\)|Thread|Core|Socket" | head -8 || echo "lscpu missing"
free -h
df -h / 2>/dev/null | grep -v tmpfs

section "NETWORK"
ip -4 addr show 2>/dev/null | grep -E "inet " | grep -v 127.0.0.1 || echo "no IPv4 (or no `ip`)"
ip -6 addr show 2>/dev/null | grep -E "inet6 " | grep -v ::1 | grep -v fe80 || echo "no IPv6"
ip route 2>/dev/null | head -5
have curl && printf "pub-v4: " && curl -s --max-time 5 -4 ifconfig.me 2>/dev/null || echo "n/a"
printf "pub-v6: " && curl -s --max-time 5 -6 ifconfig.me 2>/dev/null || echo "n/a"

section "GPU"
if have nvidia-smi; then
  nvidia-smi --query-gpu=name,memory.total,memory.used --format=csv 2>/dev/null
else
  have lspci && lspci 2>/dev/null | grep -i 'vga\|3d' || echo "no GPU detected"
fi

section "CONTAINERS"
have docker && {
  docker --version
  docker ps --format "table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}" 2>/dev/null
} || echo "no docker"

section "LISTENERS"
have ss && ss -tlnp 2>/dev/null | grep LISTEN | head -20 \
  || (have netstat && netstat -tlnp 2>/dev/null | grep LISTEN | head -20) \
  || echo "no ss/netstat"

section "TOOLCHAIN"
echo "Python: $(python3 --version 2>&1 || echo 'none')"
for c in git curl wget vim nano jq htop tmux ssh rsync node npm; do
  have "$c" && printf "%-8s %s\n" "$c" "$(command -v "$c")"
done

section "CLOUD-META"
have curl && {
  echo -n "AWS:    "; curl -s --max-time 2 -4 http://169.254.169.254/latest/meta-data/instance-id 2>/dev/null || echo "n/a"
  echo -n "Azure:  "; curl -s --max-time 2 -4 -H "Metadata:true" "http://169.254.169.254/metadata/instance?api-version=2021-02-01" 2>/dev/null || echo "n/a"
  echo -n "GCP:    "; curl -s --max-time 2 -4 -H "Metadata-Flavor: Google" "http://169.254.169.254/computeMetadata/v1/instance/id" 2>/dev/null || echo "n/a"
} || echo "no curl"
