#!/bin/bash

#
# Devices used in test
#
devices=(/dev/sda1 /dev/sdb1 /dev/sdc1 /dev/sdd1)

# Device that will be overwritten with garbage
index=0

# Pull in all MD RAID modules and dm-raid
modprobe dm-raid

# RAID level must be specified
if [ -z $1 ]; then
	echo "$0 <raid-level>"
	exit 1
fi

# Select a device to be overwritten with garbage (default = 0)
if [ ! -z $2 ]; then
	index=$2
fi

# Create MD array
if ! mdadm --create /dev/md0 --level=$1 --raid-devices=4 --size=100M ${devices[*]}; then
	echo "Failed to create"
	exit 1
fi

# Wait for initial sync
while [ `cat /sys/block/md0/md/sync_action` != "idle" ]; do
	echo "	Waiting for `cat /sys/block/md0/md/sync_action` to complete"
	sleep 1
done

mdadm --misc -D /dev/md0 | grep state

echo -n "RAID$1 mismatch count after creation     : "
cat /sys/block/md0/md/mismatch_cnt

mdadm --stop /dev/md0

echo "Writing garbage to one of the MD devices..."
dd if=/dev/urandom of=${devices[$index]} bs=1M count=10 seek=50 >& /dev/null

mdadm --assemble /dev/md0 ${devices[*]}
mdadm --misc -D /dev/md0 | grep state

while [ `cat /sys/block/md0/md/sync_action` != "idle" ]; do
	echo "	Waiting for `cat /sys/block/md0/md/sync_action` to complete"
	sleep 1
done

echo -n "RAID$1 mismatch count after reactivation : "
cat /sys/block/md0/md/mismatch_cnt
echo "check" > /sys/block/md0/md/sync_action

while [ `cat /sys/block/md0/md/sync_action` != "idle" ]; do
	echo "	Waiting for `cat /sys/block/md0/md/sync_action` to complete"
	sleep 1
done

echo -n "RAID$1 mismatch count after data-check   : "
cat /sys/block/md0/md/mismatch_cnt

if [ `cat /sys/block/md0/md/mismatch_cnt` -eq 0 ]; then
	mdadm --stop /dev/md0
	echo "***** mismatch_cnt should not be zero !!!!!!"
	exit 1
fi

mdadm --stop /dev/md0
