#!/bin/bash
# Chrome OS sensor/thermal info collector
# Run in Chrome OS shell (Ctrl+Alt+T, type 'shell' if developer mode)
# Output saved to /tmp/ or current dir if writable

OUTDIR="/tmp"
if [ -w . ]; then OUTDIR="."; fi
TS=$(date +%Y%m%d_%H%M%S)
OUT="$OUTDIR/sensor_report_$TS.txt"

exec 1> >(tee -a "$OUT") 2>&1

echo "=========================================="
echo "Chrome OS Sensor/Thermal Report"
echo "Date: $(date)"
echo "Machine: $(cat /etc/lsb-release 2>/dev/null | grep -E 'CHROMEOS_RELEASE_BOARD|CHROMEOS_DEVICETYPE' || uname -a)"
echo "=========================================="
echo ""

echo "--- 1. ectool temps (EC sensors) ---"
if command -v ectool >/dev/null 2>&1; then
    ectool temps 2>/dev/null || echo "ectool temps failed"
else
    echo "ectool not found"
fi
echo ""

echo "--- 2. ectool tempsinfo (all sensors, if available) ---"
if command -v ectool >/dev/null 2>&1; then
    ectool tempsinfo 2>/dev/null || echo "ectool tempsinfo not available"
fi
echo ""

echo "--- 3. Thermal zones (/sys/class/thermal) ---"
if [ -d /sys/class/thermal ]; then
    for tz in /sys/class/thermal/thermal_zone*; do
        [ -d "$tz" ] || continue
        n=$(basename "$tz")
        type=$(cat "$tz/type" 2>/dev/null)
        temp=$(cat "$tz/temp" 2>/dev/null)
        if [ -n "$temp" ] && [ "$temp" != "0" ]; then
            c=$((temp / 1000))
            echo "$n: $type = ${c} C (raw $temp mC)"
        else
            echo "$n: $type = N/A"
        fi
    done
else
    echo "/sys/class/thermal not found"
fi
echo ""

echo "--- 4. Hwmon devices ---"
if [ -d /sys/class/hwmon ]; then
    for h in /sys/class/hwmon/hwmon*; do
        [ -d "$h" ] || continue
        name=$(cat "$h/name" 2>/dev/null)
        echo "--- $h ($name) ---"
        for t in "$h"/temp*_input; do
            [ -f "$t" ] || continue
            label=$(cat "${t%_input}_label" 2>/dev/null || echo "temp")
            val=$(cat "$t" 2>/dev/null)
            [ -n "$val" ] && echo "  $label: $((val / 1000)) C"
        done
    done
else
    echo "/sys/class/hwmon not found"
fi
echo ""

echo "--- 5. dmesg (cros_ec, thermal, hwmon) ---"
dmesg 2>/dev/null | grep -iE 'cros_ec|thermal|hwmon|sensor|peci' | tail -80 || echo "dmesg not available"
echo ""

echo "--- 6. Fan (if ectool available) ---"
if command -v ectool >/dev/null 2>&1; then
    ectool pwmgetfanrpm all 2>/dev/null || true
    ectool pwmgetduty 0 2>/dev/null || true
fi
echo ""

echo "--- 7. CPU info ---"
cat /proc/cpuinfo 2>/dev/null | grep -E 'model name|Hardware' | head -2
echo ""

echo "=========================================="
echo "Report saved to: $OUT"
echo "To copy from Chrome OS: use 'cat $OUT' or Files app if in Downloads"
echo "=========================================="
