#!/bin/sh
#
# Author Pavel Mironchik <tibor@tut.by>

. /etc/init.d/functions

EVMS_RECONFIG="no"
SourceIfNotEmpty /etc/sysconfig/evms 
#[ -n "`mount | egrep 'type[[:space:]]proc' `" ] || exit

reconfig() {

    [ -s /etc/evms.conf ] || exit 1
    [ -e /proc/partitions ] || exit 1

    if  is_yes "$EVMS_RECONFIG"  ; then

	tmpfile=`mktemp` || exit 1
			
	/bin/gawk '

	function InitVars() { 
	secflag=0;
	include_reached=0;
	passeline = 0;
	}


	function get_partitions() {
	    retval = "";
	    FS = " ";
	    getline < "/proc/partitions";
	    while(getline < "/proc/partitions") {
		gsub(/[0-9]+/,"",$4);
		gsub(/ +/,"",$4);
		if((index($4,"md")==0) && (index(retval,$4)==0)) {
		    retval = sprintf("%s %s",$4,retval);
		}
	    }
	    FS = "";
	    return retval;
	}

	function EnterSection() { secflag=1 }
	function LeaveSection() { secflag=0 }
	function ProcessSection() { return secflag; }
	function pass_line() { passeline=1 }
	function check_line_to_pass() { 
	    if(passeline)
	    {
		passeline=0;
		return 0;
	    }
	    return 1;
	}


	BEGIN {
	    FS="";
	    RS="\n";
	    InitVars()
	}


	/^[[:space:]]*legacy_devices/ {  EnterSection() }

	/^[^#]*\}/ {
	    LeaveSection();
	}

 	/^[[:space:]]*include/ {
	    if( ProcessSection()) {
		print "    include = [ " get_partitions() "]";
		pass_line();
	    }
	}

	{
	    if(check_line_to_pass())
	    {
		print $0;  # just waste to stream
	    }
	}

	'  /etc/evms.conf > $tmpfile || exit 1

	mv $tmpfile /etc/evms.conf
    fi
}

activate() {
    i=0
    tmp=`/sbin/evms_activate`
    while [ ! -z "$tmp" ]; do
	let i=$i+1
	[ "$i" == "12" ] && break
    done
}

case "$1" in
    init)
	reconfig
	activate
    ;;
    reconfig)
	reconfig
    ;;
    activate)
	activate
    ;;
    *)
	msg_usage "${0##*/} {init|reconfig|activate}"
esac
