#!/bin/bash
# RunTheTests Mac collector — rtt-collect.sh — v1.0.0
#
# Reads this Mac's hardware and health figures and writes ONE file,
# runthetests-report.json, in the current folder. It makes NO network
# requests, sends nothing anywhere, installs nothing and changes nothing.
# Read it before running it — being readable is the point of shipping
# this as a script rather than a program.
#
# Run it:   bash rtt-collect.sh
# Then drag the JSON it writes onto
# https://runthetests.com/repair/pc-hardware-report/
#
# Uses only tools that ship with macOS: system_profiler, sysctl, df, vm_stat
# and the python3 that comes with the developer tools. If python3 is missing,
# macOS offers to install the (free) command line tools the first time.

set -u

if ! command -v python3 >/dev/null 2>&1; then
  echo "python3 is needed to assemble the report and was not found."
  echo "macOS will offer to install the free Command Line Tools: run  xcode-select --install"
  exit 1
fi

OUT="runthetests-report.json"

# Everything is gathered first, into temp files, so the python step only
# assembles — it runs no commands of its own.
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

system_profiler -json SPHardwareDataType  > "$TMP/hw.json"       2>/dev/null
system_profiler -json SPSoftwareDataType  > "$TMP/sw.json"       2>/dev/null
system_profiler -json SPDisplaysDataType  > "$TMP/gpu.json"      2>/dev/null
system_profiler -json SPPowerDataType     > "$TMP/power.json"    2>/dev/null
system_profiler -json SPNVMeDataType      > "$TMP/nvme.json"     2>/dev/null
system_profiler -json SPSerialATADataType > "$TMP/sata.json"     2>/dev/null
system_profiler -json SPStorageDataType   > "$TMP/storage.json"  2>/dev/null
sysctl -n hw.memsize                      > "$TMP/memsize"       2>/dev/null
sysctl -n hw.physicalcpu                  > "$TMP/pcpu"          2>/dev/null
sysctl -n hw.logicalcpu                   > "$TMP/lcpu"          2>/dev/null
sysctl -n machdep.cpu.brand_string        > "$TMP/cpubrand"      2>/dev/null
sysctl -n kern.boottime                   > "$TMP/boottime"      2>/dev/null
df -k /                                   > "$TMP/dfroot"        2>/dev/null
vm_stat                                   > "$TMP/vmstat"        2>/dev/null

python3 - "$TMP" "$OUT" << 'PYEOF'
import json, sys, os, re, time
from datetime import datetime, timezone

tmp, out = sys.argv[1], sys.argv[2]
notes = []

def load(name):
    try:
        with open(os.path.join(tmp, name)) as f:
            return json.load(f)
    except Exception:
        return {}

def slurp(name):
    try:
        with open(os.path.join(tmp, name)) as f:
            return f.read().strip()
    except Exception:
        return ''

hw    = (load('hw.json').get('SPHardwareDataType') or [{}])[0]
sw    = (load('sw.json').get('SPSoftwareDataType') or [{}])[0]
gpus  = load('gpu.json').get('SPDisplaysDataType') or []
power = load('power.json').get('SPPowerDataType') or []
stor  = load('storage.json').get('SPStorageDataType') or []
nvme  = load('nvme.json').get('SPNVMeDataType') or []
sata  = load('sata.json').get('SPSerialATADataType') or []

report = {
    'schema': 'runthetests-pc-report',
    'version': 1,
    'generated': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
    'collector': {'script': 'rtt-collect.sh', 'version': '1.0.0', 'elevated': os.geteuid() == 0},
}

# ── OS ───────────────────────────────────────────────────────────────
uptime_h = None
boot = slurp('boottime')
m = re.search(r'sec = (\d+)', boot)
if m:
    uptime_h = round((time.time() - int(m.group(1))) / 3600, 1)
report['os'] = {
    'platform': 'macos',
    'name': sw.get('os_version') or 'macOS',
    'version': sw.get('os_version'),
    'arch': hw.get('chip_type') and 'arm64' or None,
    'uptime_hours': uptime_h,
    'model': hw.get('machine_model'),
    'model_name': hw.get('machine_name'),
}

# ── CPU ──────────────────────────────────────────────────────────────
report['cpu'] = {
    'model': slurp('cpubrand') or hw.get('chip_type') or hw.get('cpu_type'),
    'cores_physical': int(slurp('pcpu') or 0) or None,
    'cores_logical': int(slurp('lcpu') or 0) or None,
}

# ── Memory ───────────────────────────────────────────────────────────
mem_total = int(slurp('memsize') or 0)
free_mb = None
vm = slurp('vmstat')
m = re.search(r'page size of (\d+)', vm)
pf = re.search(r'Pages free:\s+(\d+)', vm)
if m and pf:
    free_mb = round(int(pf.group(1)) * int(m.group(1)) / 1048576)
report['memory'] = {
    'total_mb': round(mem_total / 1048576) if mem_total else None,
    'free_mb': free_mb,
    'modules': [],
}
if free_mb is not None:
    notes.append('macOS keeps memory deliberately full of cache; a low free figure is normal and not a fault.')

# ── Storage devices ──────────────────────────────────────────────────
disks = []
for bus, name in ((nvme, 'NVMe'), (sata, 'SATA')):
    for controller in bus:
        for item in controller.get('_items', []):
            size_gb = None
            m = re.search(r'([\d.,]+)\s*(GB|TB)', str(item.get('size', '')))
            if m:
                size_gb = float(m.group(1).replace(',', '.')) * (1000 if m.group(2) == 'TB' else 1)
            smart = item.get('smart_status')
            disks.append({
                'model': (item.get('device_model') or item.get('_name') or 'unknown').strip(),
                'size_gb': round(size_gb, 1) if size_gb else None,
                'media': 'SSD' if 'SSD' in str(item.get('device_model', '')) or bus is nvme else 'Unknown',
                'bus': name,
                'health': {'Verified': 'Healthy', 'Failing': 'Unhealthy'}.get(smart, smart or 'unknown'),
                'temperature_c': None,
                'wear_pct': None,
                'power_on_hours': None,
            })
if not disks:
    notes.append('No internal drive details were readable from system_profiler.')
report['storage'] = disks

# ── Volumes ──────────────────────────────────────────────────────────
vols = []
for item in stor:
    try:
        size = item.get('size_in_bytes'); free = item.get('free_space_in_bytes')
        if item.get('mount_point') in ('/', '/System/Volumes/Data') and size:
            vols.append({
                'drive': item.get('mount_point'),
                'fs': item.get('file_system'),
                'size_gb': round(size / 1e9, 1),
                'free_gb': round((free or 0) / 1e9, 1),
            })
    except Exception:
        pass
report['volumes'] = vols

# ── GPU ──────────────────────────────────────────────────────────────
report['gpu'] = [{
    'model': g.get('sppci_model') or g.get('_name'),
    'vram_mb': None,
    'driver': None,
    'driver_date': None,
} for g in gpus]

# ── Battery ──────────────────────────────────────────────────────────
battery = {'present': False}
for item in power:
    if 'sppower_battery_charge_info' in item or 'sppower_battery_health_info' in item:
        health = item.get('sppower_battery_health_info', {})
        charge = item.get('sppower_battery_charge_info', {})
        model = item.get('sppower_battery_model_info', {})
        battery = {
            'present': True,
            'status': health.get('sppower_battery_health'),
            'cycle_count': health.get('sppower_battery_cycle_count'),
            'max_capacity_pct': None,
            'charge_pct': charge.get('sppower_battery_state_of_charge'),
        }
        raw_max = health.get('sppower_battery_health_maximum_capacity')
        if raw_max:
            m = re.search(r'(\d+)', str(raw_max))
            if m:
                battery['max_capacity_pct'] = int(m.group(1))
        break
report['battery'] = battery

report['network'] = []
notes.append('Network adapters, disk wear and temperatures are not exposed to user-space tools on macOS; what the system reports is included.')

report['notes'] = notes
with open(out, 'w') as f:
    json.dump(report, f, indent=1)
print()
print(f'Report written to: {os.path.abspath(out)}')
print('Nothing was sent anywhere. Drag the file onto')
print('https://runthetests.com/repair/pc-hardware-report/ to read it.')
PYEOF
