#!/bin/bash

# 06/05/2014, author: Maxim Suhanov

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

config='/etc/mdadm-ro.conf'

list_volumes()
{
	blkid -o device | grep -vE '^/dev/loop([[:digit:]]+|/.*)$'
}

list_loops()
{
	blkid -o device | grep -E '^/dev/loop([[:digit:]]+|/.*)$'
}

get_type()
{
	blkid -o value -s TYPE "$1"
}

lo_setup()
{
	loopinfo=`losetup -j "$1"`
	if [ -z "$loopinfo" ]; then
		losetup -r -f "$1" 2> /dev/null # Do not remove "-r"!
		if [ $? != 0 ]; then
			echo "Cannot setup loop device! $1 will be ignored..."
		fi
	else
		echo "$1 is already on loop device!"
	fi
}

activate_raid()
{
	for volume in `list_volumes`; do
		volume_type=`get_type "$volume"`
		if [ `echo "$volume_type" | grep '^linux_raid'` ]; then
			lo_setup "$volume"
		fi
	done

	echo "Running 'mdadm -As'..."; mdadm -As --config="$config"
	echo "Note:"
	echo "	Execute '$0 stop' to stop RAID!"
}

deactivate_raid()
{
	echo "Running 'mdadm --stop --scan'..."
	mdadm --stop --scan --config="$config"
	echo "Deleting loop devices..."
	for volume in `list_loops`; do
		volume_type=`get_type "$volume"`
		if [ `echo "$volume_type" | grep '^linux_raid'` ]; then
			losetup -d "$volume"
		fi
	done
}

if [ -z "$1" ] || [ "$1" == 'start' ]; then
	activate_raid
elif [ "$1" == 'stop' ]; then
	deactivate_raid
else
	echo "Usage: $0 [start|stop]" >&2
	exit 1
fi
