#!/bin/bash
#
# resyncmd (a substitute to watch 'cat /proc/mdastat')
# This file is part of Raider

mdresync() {	# a substitute for watch 'cat /proc/mdstat'
	local TEMPDEVMD=$TEMP/devmd
	local mdstat=/proc/mdstat
	grep -i Personalities ${mdstat} | xargs -d "\n" -I {} echo -e "${TAB_}{}"
	ls -d /sys/block/md* | xargs -I {} basename {} | sort > ${TEMPDEVMD}
	local ndevs=$(cat ${TEMPDEVMD} | wc -l)
	while read dev_md
	do
		if [ $(cat /sys/block/$dev_md/md/sync_action) == "idle" ]; then
			grep -A1 ^$dev_md ${mdstat} | xargs -d "\n" -I {} echo -e "${TAB_}{}"
			echo -e "${TAB_}"
			ndevs=$((ndevs-1))
		fi
	done <${TEMPDEVMD}
	while true
	do
		while read dvmd
		do
		    if [ $(cat /sys/block/$dvmd/md/sync_action) != "idle" ]; then
			local stat3=$(grep -A2 ^$dvmd ${mdstat} | tail -n1)
			echo $stat3 | grep -q DELAYED
			if [ $? -ne 0 ]; then
			    print_recover $dvmd
			    ndevs=$((ndevs-1))
			fi
		    fi
		done <${TEMPDEVMD}
		if [ $ndevs -lt 1 ]; then
		    break
		fi
	done
	echo -e "${TAB_}$(tail -n1 ${mdstat})"
}

print_recover() {	# print output md recover status
	devmd=$1
	local mdstat=/proc/mdstat
	grep -A1 ^$devmd ${mdstat} | xargs -d "\n" -I {} echo -e "${TAB_}{}"
	while true
	do
		local action=$(cat /sys/block/$devmd/md/sync_action)
		if [ "$action" == "idle" ]; then
			break
		fi
		local prec=$(grep -A2 ^$devmd ${mdstat} | tail -n1 )
		local prec1=" :: ${prec}"
		local larg=$(tput cols)
		echo -ne "\r${TAB_}${prec}\033[K"
		if [ ${#prec1} -gt ${larg} ]; then
			echo -ne "\r\033[1A"
		fi
		sleep 1	
	done
	echo -ne "\r\033[K\n"
	echo -ne "\r\0033[3A"
	grep -A2 ^$devmd ${mdstat} | xargs -d "\n" -I {} echo -e "${TAB_}{}\033[K"
}

