#!/bin/bash

json_array="[]"
for array in $(ls -d1 /sys/block/md* 2>/dev/null | cut -d/ -f4); do
	STATUS=$(cat /proc/mdstat | grep -E "^${array}[[:space:]]*:" | cut -d' ' -f3)
	if [[ "${STATUS}" == 'inactive' ]]; then
		item_json=$(jq -n --arg name "${array}" \
			--arg status "${STATUS}" \
			--arg total "$(cat /proc/mdstat | grep -E "^${array}[[:space:]]*:" | tr '[:blank:]' "\\n" | tail -n+4 | wc -l)" \
			--arg failed "$(cat /proc/mdstat | grep -E "^${array}[[:space:]]*:" | tr '[:blank:]' "\\n" | grep -cE '\[[[:digit:]]*\]\(F\)')" \
			--arg spare "$(cat /proc/mdstat | grep -E "^${array}[[:space:]]*:" | tr '[:blank:]' "\\n" | grep -cE '\[[[:digit:]]*\]\(S\)')" \
			'{ "name": $name, "status": $status, "total": $total, "failed": $failed , "spare": $spare }')
	else
		item_json=$(jq -n --arg name "${array}" \
			--arg status "${STATUS}" \
			--arg level "$(cat /proc/mdstat | grep -E "^${array}[[:space:]]*:" | cut -d' ' -f4)" \
			--arg raid "$(cat /proc/mdstat | grep -E -A 1 "^${array}[[:space:]]*:" | tail -1 | sed -n 's/.*\[\([[:digit:]]\)\/[[:digit:]]\].*/\1/p')" \
			--arg total "$(cat /proc/mdstat | grep -E "^${array}[[:space:]]*:" | tr '[:blank:]' "\\n" | tail -n+5 | wc -l)" \
			--arg active "$(cat /proc/mdstat | grep -E -A 1 "^${array}[[:space:]]*:" | tail -1 | sed -n 's/.*\[[[:digit:]]\/\([[:digit:]]\)\].*/\1/p')" \
			--arg failed "$(cat /proc/mdstat | grep -E "^${array}[[:space:]]*:" | tr '[:blank:]' "\\n" | grep -cE '\[[[:digit:]]*\]\(F\)')" \
			--arg spare "$(cat /proc/mdstat | grep -E "^${array}[[:space:]]*:" | tr '[:blank:]' "\\n" | grep -cE '\[[[:digit:]]*\]\(S\)')" \
			--arg missing "$(cat /proc/mdstat | grep -E -A 1 "^${array}[[:space:]]*:" | tr '[:blank:]' \\n | grep -E '^\[[U_]*\]$' | grep -co _)" \
			--arg action "$(cat /proc/mdstat | grep -E -A 2 "^${array}[[:space:]]*:" | tail -1 | sed -n 's/.*\][[:space:]]*\([[:alpha:]]\+\)[[:space:]].*/\1/p')" \
			'{ "name": $name, "status": $status, "level": $level, "raid": $raid, "total": $total, "active": $active, "failed": $failed , "spare": $spare, "missing": $missing, "action", $action }')
	fi
	json_array=$(echo "$json_array" | jq -c ". + [$item_json]")
done

echo "$json_array"
