#!/usr/bin/env python3
"""disktemp - disk temperature from SMART if smartctl is present, else /sys,
else a clear message.
Usage: disktemp [--selftest]
Tries, in order: smartctl (per block device), /sys/class/hwmon temp inputs,
/sys/class/thermal zones. Never crashes when nothing is available: it says
so plainly and exits 0."""
import argparse, glob, os, re, shutil, subprocess, sys

def smartctl_temps():
    out = {}
    if not shutil.which("smartctl"):
        return out, "smartctl not installed"
    for dev in sorted(glob.glob("/dev/sd?") + glob.glob("/dev/nvme?n?")):
        try:
            r = subprocess.run(["smartctl", "-A", dev], capture_output=True,
                               text=True, timeout=10)
        except (OSError, subprocess.TimeoutExpired):
            continue
        txt = r.stdout
        m = re.search(r"Temperature_Celsius.*?(\d+)\s*$", txt, re.M)
        if not m:
            m = re.search(r"Temperature:\s*(\d+)\s*C", txt)
        if m:
            out[dev] = int(m.group(1))
    return out, None

def sys_temps():
    out = {}
    for path in sorted(glob.glob("/sys/class/hwmon/hwmon*/temp*_input")):
        try:
            with open(path) as f:
                milli = int(f.read().strip())
            label = ""
            lab = path.replace("_input", "_label")
            if os.path.exists(lab):
                with open(lab) as f:
                    label = f.read().strip()
            name = ""
            hw = os.path.dirname(path)
            if os.path.exists(os.path.join(hw, "name")):
                with open(os.path.join(hw, "name")) as f:
                    name = f.read().strip()
            key = f"{name}:{label}" if label else name or os.path.basename(path)
            out[key] = milli / 1000.0
        except (OSError, ValueError):
            continue
    if out:
        return out, None
    for path in sorted(glob.glob("/sys/class/thermal/thermal_zone*/temp")):
        try:
            with open(path) as f:
                milli = int(f.read().strip())
            zone = os.path.basename(os.path.dirname(path))
            typ = ""
            if os.path.exists(os.path.join(os.path.dirname(path), "type")):
                with open(os.path.join(os.path.dirname(path), "type")) as f:
                    typ = f.read().strip()
            out[f"{zone} ({typ})" if typ else zone] = milli / 1000.0
        except (OSError, ValueError):
            continue
    return out, None

def selftest():
    # Must always succeed with a verdict, whatever the hardware offers.
    s, _err = smartctl_temps()
    y, _err2 = sys_temps()
    if not isinstance(s, dict) or not isinstance(y, dict):
        print("FAIL: temperature probes did not return dicts")
        return 1
    src = "smartctl" if s else ("/sys sensors" if y else "no sensor source (expected on a VM)")
    print(f"selftest: PASS (probes ran cleanly; source: {src})")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="disktemp",
        description="Disk temperature from SMART if smartctl is present, else /sys, else a clear message.")
    ap.add_argument("--selftest", action="store_true", help="run built-in checks")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    temps, err = smartctl_temps()
    if temps:
        print("disk temperatures (SMART):")
        for dev, t in sorted(temps.items()):
            warn = "  <-- HOT" if t >= 60 else ""
            print(f"  {dev:<14} {t} C{warn}")
        return 0
    temps, _ = sys_temps()
    if temps:
        print("temperatures (/sys sensors - no SMART data available):")
        for k, t in sorted(temps.items()):
            warn = "  <-- HOT" if t >= 80 else ""
            print(f"  {k:<28} {t:.1f} C{warn}")
        return 0
    print("disk temperature: unavailable on this system.")
    if err:
        print(f"  - {err}")
    print("  - no temperature sensors found under /sys/class/hwmon or /sys/class/thermal")
    print("This is normal on a VM or container with no physical disks attached.")
    print("On a physical machine, install smartmontools for SMART readings:")
    print("  apt install smartmontools   # then: smartctl -A /dev/sda")
    return 0

if __name__ == "__main__":
    sys.exit(main())
