#!/usr/bin/python3 -I
"""Serve read-only SMART requests until DriveInfo closes the input pipe.

Device names come only from lsblk and from smartctl's own RAID scan.
Keep the filters in sync with drive_info.py.
"""

import json
import os
import re
import stat
import subprocess
import sys

VIRTUAL_DISK = re.compile(r"^(zram|ram|nbd|loop|fd)\d+$|^mmcblk\d+(boot\d+|rpmb)$")
NVME_NAMESPACE = re.compile(r"^(nvme\d+)n\d+$")
RAID_TYPE = re.compile(r"^(sat\+)?(megaraid|cciss|aacraid|areca|3ware|hpt|sssraid),[0-9][0-9,/]*$")
RAID_DEVICE = re.compile(r"^/dev/[\w./-]+$")
SMART_KEYS = ("smart_status", "ata_smart_attributes", "nvme_smart_health_information_log")
LSBLK_COLUMNS = ("NAME,PATH,TYPE,TRAN,SIZE", "NAME,TYPE,TRAN,SIZE")  # second one: util-linux < 2.33


def system_tool(name):
    for directory in ("/usr/sbin", "/usr/bin", "/sbin", "/bin"):
        candidate = os.path.join(directory, name)
        if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
            return candidate
    raise FileNotFoundError(name)


def run(command, timeout):
    return subprocess.run(command, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout)


def list_disks(lsblk):
    error = "lsblk failed"
    for columns in LSBLK_COLUMNS:
        result = run([lsblk, "-J", "-b", "-d", "-o", columns], 15)
        if result.returncode == 0:
            return json.loads(result.stdout).get("blockdevices") or []
        error = result.stderr.strip() or error
    raise OSError(error)


def read_smart(smartctl, device_args, attempts):
    """Return the first answer with SMART data, else the first answer."""
    first = None
    for options in attempts:
        result = run([smartctl, "-a", "-j", *options, *device_args], 20)
        try:
            data = json.loads(result.stdout or "{}")
        except ValueError:
            data = {}
        if not isinstance(data, dict):
            data = {}
        entry = {"data": data, "error": result.stderr.strip()}
        if any(data.get(key) for key in SMART_KEYS):
            return entry
        first = first or entry
    return first


def raid_members(smartctl):
    result = run([smartctl, "--scan-open", "-j"], 60)
    members = []
    for device in json.loads(result.stdout or "{}").get("devices") or []:
        if not isinstance(device, dict):
            continue
        name, kind = str(device.get("name") or ""), str(device.get("type") or "")
        if RAID_DEVICE.match(name) and RAID_TYPE.match(kind):
            members.append((name, kind))
    return members


def read_disks():
    lsblk = system_tool("lsblk")
    smartctl = system_tool("smartctl")
    results = {}
    controllers = set()
    for disk in list_disks(lsblk):
        name = str(disk.get("name") or "")
        path = disk.get("path") or "/dev/" + name
        if (disk.get("type") != "disk" or not name or not path.startswith("/dev/")
                or VIRTUAL_DISK.match(name) or str(disk.get("size")) == "0"):
            continue
        namespace = NVME_NAMESPACE.match(name)
        if namespace:
            # SMART belongs to the controller; read it once.
            if namespace.group(1) in controllers:
                continue
            controllers.add(namespace.group(1))
        try:
            if not stat.S_ISBLK(os.stat(path).st_mode):
                continue
            # smartctl detects most USB bridges by USB ID; generic SAT is the fallback.
            attempts = [[], ["-d", "sat"]] if disk.get("tran") == "usb" else [[]]
            results[path] = read_smart(smartctl, [path], attempts)
        except (OSError, subprocess.TimeoutExpired) as exc:
            results[path] = {"error": str(exc)}
    try:
        members = raid_members(smartctl)
    except (OSError, subprocess.TimeoutExpired, ValueError, AttributeError):
        members = []
    for name, kind in members:
        try:
            results[f"{name} [{kind}]"] = read_smart(smartctl, ["-d", kind, name], [[]])
        except (OSError, subprocess.TimeoutExpired) as exc:
            results[f"{name} [{kind}]"] = {"error": str(exc)}
    return results


if __name__ == "__main__":
    for request in sys.stdin:
        if request != "refresh\n":
            break
        try:
            response = {"disks": read_disks()}
        except (OSError, subprocess.SubprocessError, ValueError) as exc:
            response = {"error": str(exc)}
        print(json.dumps(response), flush=True)
