#!/usr/libexec/platform-python
import os
import json
import sys
import re

def getDiskInfo(path):
    if not os.path.isfile(path):
        print(f"Error opening {path}. Run `dmap`.",file=sys.stderr)
        sys.exit(1)
    
    c_lines = []
    disks = []
    with open("/etc/vdev_id.conf","r") as vdev_id:
        c_lines = vdev_id.readlines()
    
    for line in c_lines:
        regex = re.search("^alias\s+(\d+-\d+)\s+(\S+)",line)
        if regex != None:
            disks.append({"dev-by-path":regex.group(2),"bay-id":regex.group(1)})
        
    for d in disks:
        d["occupied"] = os.path.islink(d["dev-by-path"])
        d["dev"] = os.path.realpath(d["dev-by-path"]) if d["occupied"] else ""
        d["disk_type"] = disk_type(d["dev"])

    return {"rows":disks}

def disk_type(device_path):
	#get the value of "/sys/block/[device_name]/queue/rotational
	#this check will return 1 if block device is a spinner, 0 if not
	device_name = os.path.basename(device_path)
	rotational_path = "/sys/block/" + device_name + "/queue/rotational"
	if not os.path.isfile(rotational_path):
		return ""
	rotational = open(rotational_path, mode='r')
	is_rotational = bool(int(rotational.read(1)))
	return ("HDD" if is_rotational else "SSD")

def main():
    diskInfo = getDiskInfo("/etc/vdev_id.conf")
    print(json.dumps(diskInfo,indent=4))


if __name__ == "__main__":
    main()
