#!/usr/bin/env python3
"""raidcheck - MD RAID status from /proc/mdstat when present.
Usage: raidcheck [--selftest]
Parses /proc/mdstat: array, level, state, active/sync and failed disks,
resync/recovery progress. On a box with no MD RAID it says so and exits 0."""
import argparse, re, sys

def parse_mdstat(text):
    """Return list of arrays: {name, level, state, disks:[(dev, flags)], progress}."""
    arrays = []
    cur = None
    for line in text.splitlines():
        m = re.match(r"^(md\d+)\s*:\s*(\w+)\s+(\S+)\s*(.*)$", line)
        if m:
            cur = {"name": m.group(1), "state": m.group(2), "level": m.group(3),
                   "extra": m.group(4), "disks": [], "progress": None}
            arrays.append(cur)
            # disks are listed on the header line itself: sda1[0] sdb1[1](F)
            for dm in re.finditer(r"(\S+?)\[\d+\](\([A-Z]\))?", m.group(4)):
                cur["disks"].append((dm.group(1), dm.group(2) or ""))
            continue
        if cur is None:
            continue
        m = re.match(r"^\s+(\d+) blocks.*$", line)
        if m:
            # the [UU] / [UUU_] health map lives on this same line
            mm = re.search(r"\[([U_]+)\]", line)
            if mm:
                cur["map"] = mm.group(1)
            continue
        # disk lines: "      sda1[0] sdb1[1](F)" etc.
        for dm in re.finditer(r"(\S+?)\[\d+\](\([A-Z]\))?", line):
            dev = dm.group(1)
            if dev in ("blocks", "super"):
                continue
            flags = dm.group(2) or ""
            cur["disks"].append((dev, flags))
        m = re.search(r"(resync|recovery|check|reshape)\s*=\s*([\d.]+%)", line)
        if m:
            cur["progress"] = f"{m.group(1)} {m.group(2)}"
        m = re.search(r"\[([U_]+)\]", line)
        if m:
            cur["map"] = m.group(1)
    return arrays

def selftest():
    sample = """Personalities : [raid1] [raid6]
md0 : active raid1 sda1[0] sdb1[1]
      104856576 blocks super 1.2 [2/2] [UU]
md1 : active raid6 sdc1[0] sdd1[1] sde1[2] sdf1[3](F)
      209715200 blocks super 1.2 [4/3] [UUU_]
      [>....................]  recovery = 12.5% (100/800) finish=1.2min speed=100K/sec
unused devices: <none>
"""
    arr = parse_mdstat(sample)
    ok = True
    if len(arr) != 2:
        print(f"FAIL: parsed {len(arr)} arrays, expected 2"); ok = False
    if ok:
        if arr[0]["level"] != "raid1" or len(arr[0]["disks"]) != 2:
            print(f"FAIL: md0 wrong: {arr[0]}"); ok = False
        if arr[1].get("map") != "UUU_":
            print(f"FAIL: md1 map {arr[1].get('map')}"); ok = False
        if arr[1].get("progress") != "recovery 12.5%":
            print(f"FAIL: md1 progress {arr[1].get('progress')}"); ok = False
        if not any(f == "(F)" for _, f in arr[1]["disks"]):
            print("FAIL: failed disk (F) not detected"); ok = False
    # live file must parse without error (even if absent)
    try:
        with open("/proc/mdstat") as f:
            live = parse_mdstat(f.read())
        print(f"live /proc/mdstat: {len(live)} array(s)")
    except OSError:
        print("live /proc/mdstat: absent (no MD RAID on this box)")
    if ok:
        print("selftest: PASS (sample mdstat parsed: raid1 UU, raid6 UUU_ + failed disk + recovery 12.5%)")
    return 0 if ok else 1

def main():
    ap = argparse.ArgumentParser(prog="raidcheck",
        description="MD RAID status from /proc/mdstat when present.")
    ap.add_argument("--selftest", action="store_true", help="run built-in checks (incl. sample mdstat)")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    try:
        with open("/proc/mdstat") as f:
            text = f.read()
    except OSError:
        print("RAID: no MD RAID present on this system (no /proc/mdstat).")
        return 0
    arr = parse_mdstat(text)
    if not arr:
        print("RAID: no MD RAID arrays configured (mdstat present but empty).")
        return 0
    healthy = True
    for a_ in arr:
        failed = [d for d, fl in a_["disks"] if "F" in fl]
        degraded = a_.get("map", "") and "_" in a_["map"]
        status = "OK" if not failed and not degraded else "DEGRADED"
        if status != "OK":
            healthy = False
        print(f"{a_['name']}: {a_['state']} {a_['level']} [{status}]")
        print(f"  disks: {', '.join(d + fl for d, fl in a_['disks'])}")
        if a_.get("map"):
            print(f"  map:   [{a_['map']}]  (U=up, _=missing)")
        if failed:
            print(f"  FAILED: {', '.join(failed)}")
        if a_.get("progress"):
            print(f"  progress: {a_['progress']}")
    return 0 if healthy else 1

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