#!/bin/bash
#
# mainfunctions (raider functions)
# This file is part of Raider

avoid_runlevel_1() {	# check if this distro cannot run raider in runlevel 1
	# check if this distro can not run in runlevel 1
	echo $DISTRO | grep -qi "opensuse"
	if [ $? -eq 0 ]; then
		return 0
	fi
	echo $DISTRO | grep -qi -e ^"Gentoo" -e ^"Sabayon"
	if [ $? -eq 0 ] && [ "$(cat $STEP_FILE)" == "3" ]; then	# in gentoos distro avoid runlevel 1 in step 3
			return 0
	fi
	return 1	
}

check_2T_metadata() {	# check 2T disks and raid metadata 0.90 incompatibility
	local mess=""
	for i in ${DISK[@]}
	do
		#total_disk_size $i
		if [ $(d_info_space_bytes $i) -gt 2000000000000 ]; then
			mess="${mess}${i} "
		fi
	done
	echo "$mess"
}

check_bug_M() {		# Mandriva-2010 and Mageia-1 bug
	# not really a bug. These distros only start 0.90 metadata devices on boot
	echo ${DISTRO} | grep -q -e "Mageia 1" -e "Mandriva Linux 2010"
	if [ $? -eq 0 ]; then
		# signal bug Mandriva/Mageia
		>$R_LIB/bugM
		return 0
	fi
	return 1
}

check_commands() {		# check if needed commands exist in the system
	local commands_needed="
	  clear
	  grep 
	  cut 
	  awk 
	  head
	  xargs
	  dd
	  readlink 
	  find 
	  sleep 
	  sed 
	  sync 
	  cat 
	  cp 
	  stat
	  mount
	  sfdisk 
	  fdisk
	  parted
	  mdadm 
	  chroot
	  hdparm
	  bc
	  rsync
	  wget"
	commands_not_exist=""
	for i in $commands_needed
	do
	  if ! type $i > /dev/null 2>&1 ; then
		commands_not_exist="$commands_not_exist $i"
	  fi
	done
	echo "$commands_not_exist"
}


check_final_errors() {	# check if variables parsed from bootloader are all set
	for i in "$vKroot" "$vInitrd"
	do
		if [ -z "$i" ]; then
			return 1
		fi
	done
}


check_initrd() {		# check which initrd builder exists in this system
	type dracut >/dev/null 2>&1			# used in Fedora and others
	if [ $? -eq 0 ]; then
		MKINITRD="dracut"
		return
	fi
	
	type mkinitcpio >/dev/null 2>&1		# used in Arch
	if [ $? -eq 0 ]; then
		MKINITRD="mkinitcpio"
		return
	fi
		
	type update-initramfs >/dev/null 2>&1	# used in Ubuntu
	if [ $? -eq 0 ]; then
		MKINITRD="update-initramfs"
		return
	fi
	
	type mkinitramfs >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		MKINITRD="mkinitramfs"
		return
	fi
	
	type mkinitrd >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		MKINITRD="mkinitrd"
		return
	fi	
	
	type genkernel >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		MKINITRD="genkernel"
		return
	fi
}


check_kernel_raid_drivers() {	# check if raid drivers are compiled in the kernel (when there is no initramfs)
	# check if module raidX exist
	modinfo "raid${RAID_TYPE}" >/dev/null 2>&1	# check if there are raid modules
	if [ $? -ne 0 ]; then
		# modinfo or module raid does not exist
		# check if it compiled in kernel
		if [ -e /proc/mdstat ]; then
			# there are raid drivers compiled in kernel
			# let's check if the one we want exists
			grep ^Personalities /proc/mdstat | grep -q "[raid${RAID_TYPE}]"
			if [ $? -eq 0 ]; then
				# raid drivers compiled in kernel
				return 0
			else
				# raid drivers not compiled
				return 1
			fi
		else
			# /proc/mdstat is created automatically if raid drivers are compiled in kernel.
			# so, in this case they are not
			return 1
		fi
	fi
	return 1	# raid drivers not compiled in kernel. Raid modules exist
}

check_need_mtab() {		# check if /etc/mtab is a softlink to /proc/mounts and we don't need to create a new mtab file
	# consider not only /proc/mounts, but also /proc/self/mounts, /proc/pidnumber/mounts
	local linkexist=$(readlink -e ${MTAB} | grep -e ^/proc -e mounts)
	if [ -n "$linkexist" ]; then
		# need no mtab file
		return 1
	fi
	# need mtab file
	return 0
}
check_raid() {		# check if raid is running in the end of step 3
	error=0
	local maxdisks
	local disks
	local degraded
	while read md
	do
		maxdisks=$(cat /sys/block/$md/md/raid_disks)
		disks=$(ls -d /sys/block/$md/md/dev-* | wc -l)
		degraded=$(cat /sys/block/$md/md/degraded)
		if [ $maxdisks -ne $disks ]; then
			printerror "Failed to add a device in /dev/$md array"
			error=$((error+1))
		fi
		if [ -e /sys/block/$md/md/degraded ]; then
			if [ $degraded -ne 0 ]; then
				printerror "Degraded /dev/$md array detected"
				error=$((error+1))
			fi
		fi
	done < <(list_mdarrays)
	return $error
}

check_root() {		# Check if you are root
	if [ $UID -ne 0 ]; then
		echo "You must be root to perform this operation"
		exit 1
	fi
}

check_runlevel_S(){		# check if runlevel is 1 or Single
	if type systemctl > /dev/null 2>&1 ; then
		systemctl -q is-active rescue.target
		if [ $? -eq 0 ]; then	
			return 0
		fi
	fi
	rl=$(runlevel | awk '{print $2}')
	rl1=$(who -r | awk '{print $2}')
	case $rl in
		S | s | 1)
			return 0
			;;
		*)
			if [ "$(runlevel)" == "unknown" ]; then
				case $RUNLEVEL in
					S | s | 1)
						return 0
						;;
					*)
					case $rl1 in
						S | s | 1)
							return 0
						;;	
						*)
							return 1
						;;
					esac
					;;
				esac
				return 0
			else
				return 1
			fi
			;;
	esac
}


check_distros_not_runlevel1() {	# check distros not allowed to run raider in runlevel 1
	# return 1 if the distro is not opensuse, or is opensuse not running runlevel 1
	echo $DISTRO | grep -qi "opensuse"
	if [ $? -eq 0 ]; then
		if (check_runlevel_S); then
			return 0
		fi
	fi
	return 1
}

check_latest_raider() {
	local latest_version=$(wget --no-cache raider.sourceforge.net/latest -q -O -)
	if [ -z "$latest_version" ]; then	# if we cannot read the latest version, use version 0
		latest_version=0
	fi
	echo $latest_version > $R_LIB/new_raider_version
	if [ "$VERSION" == "devel" ]; then
		return 0
	fi
	check_utils_versions ${VERSION} ${latest_version}
	if [ $? -ne 0 ]; then
		return 1
	else
		return 0
	fi
}

check_selinux() {		# check if selinux enabled and set autorelabel

	if (type sestatus >/dev/null 2>&1); then
		local sestatus=$(sestatus | awk 'BEGIN{FS=":"} /^SELinux status/ {print $2}' | sed "s/^[ \t]*//g")
		if [ "$sestatus" == "enabled" ]; then
			return 0	# selinux enabled
		fi
	fi
	return 1	# selinux not enabled
}


check_utils_versions() {	# compare command version number with the version wanted
	# check_utils_versions $actual_version $version_to_check_against
	# returns 0 if $actual_version greater or equal then
	# returns 1 if $actual_version is not greater then
	# e.g.: check_utils_versions $KERNEL_VERSION 2.6.18
	local actual_version=$1
	local smallest_version=$2
	local a_major=$(echo $actual_version | cut -d'.' -f1)
	a_major=${a_major:=0}
	local a_minor=$(echo $actual_version | cut -d'.' -f2)
	a_minor=${a_minor:=0}
	local a_patch=$(echo $actual_version | cut -d'.' -f3)
	a_patch=${a_patch:=0}
	local s_major=$(echo $smallest_version | cut -d'.' -f1)
	s_major=${s_major:=0}
	local s_minor=$(echo $smallest_version | cut -d'.' -f2)
	s_minor=${s_minor:=0}
	local s_patch=$(echo $smallest_version | cut -d'.' -f3)
	s_patch=${s_patch:=0}
	if [ $a_major -lt $s_major ]; then
		return 1
	elif [ $a_major -gt $s_major ]; then
		return 0
	elif [ $a_minor -lt $s_minor ]; then
		return 1
	elif [ $a_minor -gt $s_minor ]; then
		return 0
	elif [ $a_patch -lt $s_patch ]; then
		return 1
	else
		return 0
	fi
}

copy_conf_to_chroot() {		# copy configuration files to chroot mountpoint
	"cp" -f ${NEWMENULST_MD} ${MOUNTPOINT}${MENULST}
	if [ -f ${MENULST_EXTRA1} ]; then
		"cp" -f ${NEWMENULST_MD_EXTRA1} ${MOUNTPOINT}${MENULST_EXTRA1}
	fi
	"cp" -f ${NEWFSTAB} ${MOUNTPOINT}${FSTAB}
	if (check_need_mtab); then
		"cp" -f ${NEWMTAB} ${MOUNTPOINT}${MTAB}
	fi
	if [ -f ${MOUNTPOINT}${MDADM_CONF} ]; then
		"mv" -f ${MOUNTPOINT}${MDADM_CONF} ${MOUNTPOINT}${MDADM_CONF}.preraider
	fi
	"cp" -f ${NEWMDADM_CONF} ${MOUNTPOINT}${MDADM_CONF}
	if [ -f ${MKINITCPIO_CONF} ]; then
		"cp" -f ${NEW_MKINITCPIO} ${MOUNTPOINT}${MKINITCPIO_CONF}
	fi
}

create_database() {		# create system disk main database with partition information
	
	# Database format:
	# $1 - partition number
	# $2 - Partition type (primary/extended/logic)
	# $3 - Total sectors size
	# $4 - Filesystem type (ext2, ext3)
	# $5 - supported (1) types filesystem; not supported (0)
	# $6 - mountpoint (eg: /boot ) if no mount point: #
	# $7 - mdarray number to create ( 0, 1, 2...). If not supported, $7 = -1	
	# $8 - device nametype used in fstab (dev, label, uuid, by-id, by-uuid. by-path, by-label, mapper, numeric)

	# The next record is only parsed later when running create_grub1_conf
	# $9 - device nametype used in grub.conf "root=" field (dev, label, uuid, by-id, by-uuid. by-path, by-label, mapper, numeric)

	# $10 - partition flag (boot)
	# $11 - partition name in gpt partitions
	# $12 - Start sector size
	# $13 - End sector size
	
	# Database record example:
	#    +---+  +--------------+  +-------+  +------+  +---+  +-------+  +----+ +--------+ +------+ +-------+ +----------+ +-------+ +-----+
	#    | 2 |  | pr/ext/logic |  | total |  | ext3 |  | 1 |  | /boot |  | -1 | |by-path | |by-id | | flag  | | namepart | | start | | end |
	#    +---+  +--------------+  +-------+  +------+  +---+  +-------+  +----+ +--------+ +------+ +-------+ +----------+ +-------+ +-----+
	#      $1          $2             $3        $4       $5      $6        $7       $8        $9       $10          $11       $12      $13
	
	> $DISK_DB				# create partition disk database file
	> $SYSTEM_DISK			# file with the name of the system disk
	> $NON_SYSTEM_DISKS		# file with the name of new disk 

	logging "Creating a database based on ${DISK[0]}"

	MountedDevs=$(mount | awk '$1 ~ "^/dev" {print $1}' | xargs -I {} readlink -f {})
	logging "List of mounted devices:"	
	echo "$MountedDevs" >> $LOGFILE
	echo "" >> $LOGFILE
	rootdisk=$(get_system_disk)
	for i in $(list_disks)
	do
		if [ "$rootdisk" == "/dev/$i" ]; then
			# check which disk holds "/" (this is the system disk)
			echo $i > $SYSTEM_DISK
			disk1=$i
		else
			# keep other disks available
			echo $i >> $NON_SYSTEM_DISKS
		fi	
	
	done
	

	if ! [ -f $NON_SYSTEM_DISKS ] || ! [ -s $NON_SYSTEM_DISKS ]; then
		ERRORS=$((ERRORS+1))
		printing "There are no disks available to create RAID array"
	fi

	# check if disk selected in command option is not the system disk
	if [ "/dev/$disk1" != "${DISK[0]}" ]; then
		# disk selected is not system disk
		# check if it is mounted
		mounted=0
		for i in $MountedDevs; do
			echo "$i" | grep -q "${DISK[0]}"
			if [ $? -eq 0 ]; then
				# is mounted
				mounted=1
				printing "${DISK[0]} disk is mounted"
				break
			fi
		done

		if [ $mounted -eq 0 ]; then
			# maybe the disk has already a raid array
			# check if LISTARRAYS are not empty
			
			ld=$(list_mdarrays)
			devr=$(echo ${DISK[0]} | sed 's/\/dev\///g')
			busy_disk=""
			if [ -n "$ld" ]; then
				for h in $ld; do
					if (ls -1 /sys/block/$h/slaves | grep -q $devr); then
						printing "ERROR: /dev/$h uses ${DISK[0]} in a raid array"
						logging "$linearray"
						busy_disk="array"
						DISKSTATUS=( "${DISKSTATUS[@]}" "$DISK_WITH_RAID" )
					fi
				done
			else
				busy_disk="not mounted"
				printing "${DISK[0]} is not mounted!"
				DISKSTATUS=( "$DISKSTATUS[@]}" "$DISK_NOT_MOUNTED" )
			fi
			if [ "$busy_disk" == "array" ]; then
			    echoing "FATAL ERROR: Unable to perform what we want"
			    echoing "Program aborted"
			    exit 1
			elif [ "$busy_disk" == "not mounted" ]; then
			    echoing "Program aborted"
			    exit 1
			fi
			# go on without aborting, if it has raid arrays not belonging to other disk
		fi
	else
		ORIGINAL_IS_SYSTEM_DISK=1
		# this is important only if we had the option to create a raid array where the original disk would not be part of the array.
		# But meanwhile we have not that option, so, this is unusefull in this version
	fi
	

	n_mdarray=0
	first=$(echo "${DISK[0]}" | sed s"/\/dev\///"g)

	while read parts1
	do

		n=`echo $parts1 | awk -F: '{print $1}'`	# partition number
		# filesystem accepted is based on blkid names
		totalbytes=$(echo ${parts1} | awk -F: '{print $4}')
		totalbytes=$(remove_value_type ${totalbytes})	# remove "s" and let only the number
		
		if (echo ${PARTITION_TABLE_TYPE} | grep -qi "msdos"); then
			# needed to create a partition later with parted
			part_type=$(env LC_ALL=C parted ${DISK[0]} print | awk -v np=${n} '$1==np {print $5}')	
			gpt_partition_name="#"
		else
			gpt_partition_name=$(echo ${parts1} | awk -F: '{print $6}')
			if [ -z "$gpt_partition_name" ]; then
				gpt_partition_name="#"
			fi
			part_type="#"
		fi
		
		local flag
		echo ${parts1} | awk -F: '{print $7}' | sed 's/;$//g' | grep -q "boot"
		if [ $? -eq 0 ]; then
			flag="boot"
		else
			flag="#"
		fi
		local startbytes=$(echo ${parts1} | awk -F: '{print $2}')
		startbytes=$(remove_value_type ${startbytes})
		local endbytes=$(echo ${parts1} | awk -F: '{print $3}')
		endbytes=$(remove_value_type ${endbytes})

		fs_type=$(blkid -c /dev/null -s TYPE "/dev/${first}${n}" | sed -e "s/.*TYPE=//g" -e "s/\"//g" -e "s/[ ]*$//g") # filesystem type
		if [ -z "$fs_type" ]; then
			# oldest blkid don't detect lvm partitions
			# so, check against parted
			parted_machine /dev/${first} | awk -v n=${n} -F: '$1==n {print $7}' | grep -q lvm
			if [ $? -eq 0 ]; then
				fs_type="LVM2_member"
			fi
		fi
		if [ -z "$fs_type" ]; then
			fs_type="#"
		fi
	
		###       $1     $2         $3         $4 
		newlinha="$n $part_type $totalbytes $fs_type"
		sup="0"
		nmd=-1
		for a in $SUPPORTED_FS_TYPES
		do
			# Swap is supported only if SWAPRAIDER_MODE=1
			if [ "$fs_type" == "swap" ] && [ $SWAPRAIDER_MODE -eq 0 ]; then
				continue
			fi
			if [ "$a" == "$fs_type" ]; then
				sup="1" # 1 is a supported partition type. Means this must be a mdarray. 
				nmd=$n_mdarray
				n_mdarray=$((n_mdarray + 1))
				break 
			fi
		done		
		mountpoint=""

		# read each device mounted and get mountpoint if partition n is mounted
		fstabtype="#"
		mount | grep ^/dev > $TEMP/mount

		while read lmount
		do
			getdev=$(echo "$lmount" | awk '{print $1}')
			check_if_dev_is_lvm $getdev
			if [ $? -eq 0 ]; then
			    volname=$(env LC_ALL=C lvdisplay -c "$getdev" | awk 'BEGIN {FS=":"} {print $2}')
			    namedev=$(env LC_ALL=C pvs | awk -v volname="$volname" '$2 ~ volname {print $1}')
			else
			    namedev=$(readlink -f $(echo $lmount | awk '{print $1}'))
			fi
			
			if [ "/dev/${first}${n}" == "$namedev" ]; then
				mountpoint=$(echo $lmount | awk '{print $3}')
				fstabtype=$(get_mountpoint_fstab_nametype "$mountpoint")
				break
			fi
		done < $TEMP/mount
		
		# check if "n" is a swap partition and save his nametype to the database.
		if [ "$fs_type" == "swap" ]; then
			#get type of name
			fstabtype=$(get_mountpoint_fstab_nametype "swap")
		fi
		
		if [ -z $mountpoint ]; then
			mountpoint="#"  # signs no mountpoint
		fi
		
		#           $1-$4    $5     $6        $7      $8     $9 $10           $11            $12       $13
		newlinha="$newlinha $sup $mountpoint $nmd $fstabtype # $flag $gpt_partition_name $startbytes $endbytes"	
		# the "#" in field $9 is the default grub devtype name
		# that will be changed later in create_grub_conf (add_grub_devtype_to_db())

		echo $newlinha >> $DISK_DB
	done < <(parted_machine "/dev/$first" u s | tail -n+3)
}


create_dirs() {		# create directories needed to run single2 raid1
	"rm" -fR $DB_DIR
	mkdir -p $LIST_DISKS
	mkdir -p $LIST_ARRAYS
	mkdir -p $TEMP
	mkdir -p $CONF_DIR
}

create_fstab() {	# create new /etc/fstab file

	local dv
	local vg
	local lv
	local new_vg
	local typeoflvm
	local new_dv
	declare -a new_dv_b
	local mp
	local md
	local temp_DISK_DB
	if [ $BOOTP_MODE -eq 1 ]; then
		temp_DISK_DB=$DISK_DB_VIRTUAL
	else
		temp_DISK_DB=$DISK_DB
	fi

	>$NEWFSTAB.tmp
	"rm" -f $SWAP_NEED_FORMAT >/dev/null 2>&1	# remove if exists
	echo "# $FSTAB created by $PROGRAM_NAME Ver: $VERSION" > $NEWFSTAB
	cat $FSTAB >> $NEWFSTAB
	if (check_need_mtab); then
		"cp" -pf $MTAB $NEWMTAB
	fi

	while read dskl
	do
		if (echo "$dskl" | grep -q -e ^/dev -e ^"UUID=" -e ^"LABEL=" ); then
			mp=$(echo "$dskl" | awk '{print $2}')	# mountpoint
			dv=$(echo "$dskl" | awk '{print $1}')	# device
			fsys=$(echo "$dskl" | awk '{print $3}')	# filesystem
			if (echo "$dskl" | grep -q ^"LABEL="); then 
				dv=$(echo $dv | sed 's/^LABEL=//g')
				#dv=$(blkid -c /dev/null -L $dv)
				dv=$(blkid -c /dev/null | grep "LABEL=\"$dv\"" | cut -d':' -f1)
			elif (echo "$dskl" | grep -q ^"UUID="); then
				dv=$(echo $dv | sed 's/^UUID=//g')
				#dv=$(blkid -c /dev/null -U $dv)
				dv=$(blkid -c /dev/null | grep "UUID=\"$dv\"" | cut -d':' -f1)	# parse device name /dev/sdX
			fi
			# check lvm2
			if (check_if_dev_is_lvm $dv); then
				vg="$(lvs --noheadings $dv | awk '{print $2}')"
				lv="$(lvs --noheadings $dv | awk '{print $1}')"	
				new_vg="${vg}${RAID_EXT}"
				typeoflvm=$(echo $dv | cut -d'/' -f3)
				if [ "$typeoflvm" == "mapper" ]; then
					new_dv="/dev/mapper/${new_vg}-${lv}"
					new_dv_mtab="$new_dv"
				else
					new_dv="/dev/${new_vg}/${lv}"
					new_dv_mtab="/dev/mapper/${new_vg}-${lv}"
				fi
			else	# not lvm2
				vg=""
				if [ "$mp" == "swap" ] || [ "$fsys" == "swap" ]; then
					md=$(awk '$4 == "swap" {if ($7 == "#") print -1; else print $7}' $temp_DISK_DB)
				else
					md=$(awk -v mp="$mp" '$6 == mp {if ($7 == "#") print -1; else print $7}' $temp_DISK_DB)
				fi
				md=${md:=-1}	# if md is empty (no mountpoint with that name) then md=-1
				
				if [ $md -lt 0 ]; then
					# not raid
					# transform labels and uuid's to device /dev/sdX
					new_dv=$(realdev "$dv")	# the same as before
					new_dv_mtab="$new_dv"
					if [ "$mp" == "swap" ] || [ "$fsys" == "swap" ]; then
						if [ $SWAPRAIDER_MODE -eq 0 ]; then
							if [ $BOOTP_MODE -eq 1 ]; then
								# change partition number if BOOTP_MODE
								newmp=$(awk '$4=="swap" {print $1}' $DISK_DB_VIRTUAL)
								new_dv=${DISK[0]}${newmp}
								for ((f=1; f<${#DISK[@]}; f++))
								do
									new_dv_b[${f}-1]=${DISK[$f]}${newmp}
								done						
							else
								for ((f=1; f<${#DISK[@]}; f++))
								do
									new_dv_b[${f}-1]=${DISK[$f]}$(echo $new_dv | sed 's/.*[hs]d[a-z]//g')
								done
							fi
						fi
					fi
				else
					new_dv="/dev/md${md}"	# raid
					new_dv_mtab=${new_dv}
				fi
			fi		
			if [ -n "$new_dv" ]; then	
				echo -e "$dskl" | awk -v newdev="$new_dv" '{$1 = newdev;print}' >> $NEWFSTAB.tmp
			else
				echo -e "$dskl" >> $NEWFSTAB.tmp
			fi
			if [ "$fsys" != "swap" ]; then	# mtab does not have swap mount point
				if (check_need_mtab); then
					if [ -n "$mp" ] && [ -n "$new_dv_mtab" ]; then
						awk -v mp="$mp" -v ndm="$new_dv_mtab" '$2 == mp {$1 = ndm}{print}' $NEWMTAB > $NEWMTAB.tmp
					fi
					"mv" -f $NEWMTAB.tmp $NEWMTAB
				fi
			fi
			local swp
			# it needs duplicate swap partition in the other disk if swapraider=0, unless it is a lvm swap
			if [ $SWAPRAIDER_MODE -eq 0 ] && [ "$fsys" == "swap" ] && [ -z "$vg" ]; then
				for ((f=1; f<${#DISK[@]}; f++))
				do
					if [ ${f} -eq $((${#DISK[@]}-1)) ]; then
						swp=${SWAP_PRFIX}
					else
						swp=""
					fi
					# add to the next swaps:
					#   ####add_swap /dev/sdX
					echo -e "${dskl}" | awk -v newdev="${swp}${new_dv_b[${f}-1]}" '{$1 = newdev;print}' >> $NEWFSTAB.tmp
					disk1_slashed=$(echo ${DISK[$f]} | sed 's/\//\\\//g')
					echo ${new_dv_b[$f-1]} | sed "s/^$disk1_slashed//g" > $SWAP_NEED_FORMAT
				done
			fi
		else
			echo "$dskl" >> $NEWFSTAB.tmp
		fi
	done < $NEWFSTAB
	if [ $BOOTP_MODE -eq 1 ]; then
		# add boot partition to fstab
		fst=$(awk '$6=="/boot" {print $4}' $DISK_DB_VIRTUAL)
		local boot_mountpoint="/dev/md0 /boot ${fst} defaults 0 1"
		echo $boot_mountpoint >> ${NEWFSTAB}.tmp
		if (check_need_mtab); then
			boot_mtab="/dev/md0 /boot ${fst} rw,relatime,acl 0 0"
			echo $boot_mtab >> $NEWMTAB
		fi
	fi
	"mv" -f $NEWFSTAB.tmp $NEWFSTAB
}

create_mdadm_conf() {		# Create a mdadm.conf file

	if [ -d /etc/mdadm ]; then
		MDADM_CONF=/etc/mdadm/mdadm.conf
	else
		MDADM_CONF=/etc/mdadm.conf
	fi
	logging "Creating new mdadm.conf in $NEWMDADM_CONF"
	echo "DEVICE partitions" > $NEWMDADM_CONF
	
	# create mdadm.conf, and fix a bug related with metadata=0.90
	mdadm -Dsb | sed s"/metadata=00\.90/metadata=0\.90/"g >> $NEWMDADM_CONF		
	printfile "New $MDADM_CONF created:" $NEWMDADM_CONF
}


create_mdarray() {		# create raid md arrays	
	#  create_mdarray ${nraid} ${npart} ${raid_type} ${boot_partition}
	local mdname=md$1
	local mdarray=/dev/md$1
	local mdarray_bug=/dev/md/$1	
	local bug=0
	local partition=$2
	local raid_type=$3
	local boot=$4
	local metadata90=""
	local disks=""
	for (( i=1; i<${#DISK[@]} ; i++))
	do
		disks="${disks}${DISK[$i]}${partition} "
	done

	## In Grub2 v1.99 we don't need metadata=0.90. Also GPT with disks > 2Tb need metadata=1.2	
	local mesg=" "

	if [ "$BOOTLOADER" == "LILO" ]; then	# LILO only supports metadata 0.90
		metadata90='--metadata=0.90'
	elif ! (check_utils_versions $GRUB_VERSION 1.99.0) && [ "$boot" == "yes" ]; then
		metadata90='--metadata=0.90'	# /boot partition in grub1 needs metadata 0.90
										# some 1.97 does not need 0.90, but 
	elif [ $GRUBNAME == "1" ]; then
		check_bug_M
		if [ $? -eq 0 ]; then
			metadata90='--metadata=0.90'	# if bug_M metadata 0.90 for all arrays, not only /boot
		fi
	fi
	sleep 1	
	# kludge to grub2-install bug in version '1.99~rc1-13ubuntu3' (does not detect /dev/mdX devices, only /dev/md/X )
	if [ "$GRUBNAME" == "2" ]; then
		if $GRUB_INSTALL --version | awk '{print $3}' | grep -q "1.99~rc1-13ubuntu3" && [ -z "$metadata90" ]; then
			printing "Detected grub bug #803749. Don't worry! Raider knows how to deal with it!"
			printing "(see https://bugs.launchpad.net/ubuntu/+source/mdadm/+bug/803749)"
			mdarray=$mdarray_bug	# This grub2 version only detects this type of md device and neglects /dev/mdX
									# It is used in Ubuntu-11.4, LinuxMint-11, ...
		fi
	fi
	
	local total_disks=${#DISK[@]}
	###  --assume-clean in raid6 only
	local aclean=""
	if [ ${raid_type} -eq 6 ]; then
		aclean=' --assume-clean'
	fi
	
	printing "Creating raid ${raid_type} array ${mdarray} with devices $disks"
	logging "mdadm --quiet --create $mdarray $metadata90 --level=${raid_type} -n ${total_disks}${aclean} -x 0 ${disks} missing"

	echo "y" | mdadm --quiet --create ${mdarray} ${metadata90} --level=${raid_type} -n ${total_disks}${aclean} -x 0 ${disks} missing >>$LOGFILE 2>&1
	sleep 2
	
	local timeout=5 # seconds
	local timecount=0
	local md__dev="/sys/block/${mdname}"
	local md__ver="/sys/block/${mdname}/md/metadata_version"
	local md__level="/sys/block/${mdname}/md/level"
	while true
	do
		if [ -d ${md__dev} ] && [ -e ${md__ver} ] && [ -e ${md__level} ]; then
			local mtd=$(cat ${md__ver})
			local mlev=$(cat ${md__level})
			local sda_err=0
			local sda_min
			local dev_state
			for sda in ${disks}
			do
				sda_min=$(echo $sda | sed 's/\/dev\///g')
				if ! [ -e /sys/block/${mdname}/md/dev-${sda_min}/state ]; then
					timecount=$((timecount+1))
					if ((timecount>timeout)); then
						return 1
					fi
					sleep 1
					continue
				fi				
				dev_state=$(cat /sys/block/${mdname}/md/dev-${sda_min}/state)
				if [ "$dev_state" != "in_sync" ] && [ "$dev_state" != "spare" ]; then
					# spare is created in raid6.
					sda_err=1
					break
				fi
			done
			mlev=$(echo $mlev | sed 's/[a-z]/\u&/')
			if [ ${sda_err} -eq 1 ]; then
				printing "Detected ${sda} as a \"${dev_state}\" device!!!"
				return 1
			fi
			printing "${mlev} array $mdarray (metadata=${mtd}) started..."
			break
		else
			timecount=$((timecount+1))
			if ((timecount>timeout)); then
				return 1
			fi
			sleep 1	
		fi
	done
}


delete_disk() {		# erase disk function

	local disk_to_clean=$1
	local VG
	kernel_messages_off
	p_table_type=$(parted_machine ${disk_to_clean} | grep ^"${disk_to_clean}" | awk -F: '{print $6}')
	if [ "$p_table_type" == "unknown" ]; then
		# there is nothing to delete if partition table not detected
		return 1
	fi

	# Check LVM2 Volume Groups in the disk to delete and remove them
	if (type pvs >/dev/null 2>&1); then
		while read pvol
		do
			if (echo $pvol | grep -q $disk_to_clean); then
				VG=$(echo $pvol | awk '{print $2}')	# get Volume Group from this partition
				logging "Remove volume group: $VG"
				vgchange -a n $VG >>$LOGFILE 2>&1
				vgremove --force $VG >>$LOGFILE 2>&1
			
			elif (echo $pvol | grep -q /dev/md); then
				local mdx=$(echo $pvol | awk '{print $1}' | sed 's/\/dev\///g')
				local dc=$(echo $disk_to_clean | sed 's/\/dev\///g')
				local mdst=$(awk -v mdx="$mdx" -v dc="$dc" '$1 == mdx && $0 ~ dc {print}' /proc/mdstat)
				if [ -n "$mdst" ]; then
					VG=$(echo $pvol | awk '{print $2}')
					logging "Remove volume group: $VG"
					vgchange -an $VG >>$LOGFILE 2>&1
					vgremove --force $VG >>$LOGFILE 2>&1
				fi
			fi
		done < <(pvs | grep -e /dev/md -e $disk_to_clean)
	fi
	
	# Check mdarrays. Stop them and zero-superblock the partitions
	
	local dtc1=$(echo $disk_to_clean | sed 's/\/dev\///g')
	local dtc="^$dtc1.+"
	for i in $(awk '$4 ~ "'"$dtc"'" {print $4}' /proc/partitions)
	do
		if (mdadm --examine /dev/$i >/dev/null 2>&1) ; then		# check if $i is part of a raid array
			local md=$(awk -v a="$i" '$0 ~ a {print $1}' /proc/mdstat)
			if [ -n "${md}" ]; then
				logging "Partition /dev/$i is part of the /dev/$md array"
				logging "Stop the /dev/$md array"
				mdadm --stop --force /dev/${md} >> $LOGFILE 2>&1 
				sleep 1
			fi
			logging "Delete superblock from /dev/$i"	# delete partition superblock
			mdadm -v --zero-superblock --force /dev/$i >> $LOGFILE 2>&1
			sleep 1
		fi
		if type wipefs >/dev/null 2>&1 ; then 
			# older distros like Centos-5 don't have this tool
			wipefs -a /dev/$i >> $LOGFILE 2>&1
		fi
	done
		
	# to remove the partition table, use this method:
	# change partition table to msdos (if it is different from it)
	# then zero the MBR (first 512b sector)
	if [ "$p_table_type" == "gpt" ]; then
		logging "Changing to MBR partition table"
		parted -s ${disk_to_clean} mklabel msdos
	fi
	# Delete the partition table
	logging "Deleting the partition table"
	dd if=/dev/zero of=${disk_to_clean} bs=512 count=1 >>$LOGFILE 2>&1
	sync
	sleep 1
	sfdisk -R -f ${disk_to_clean}	# inform kernel about deleted partition
	kernel_messages_on
}


fstab_type_of_devicename() {	# get fstab type of device  
	# e.g.: fstab_type_of_devicename /dev/mapper/VlG_root_v
	mp=$1
	devname="$(awk -v mp="$mp" '$2 == mp {print $1}' $FSTAB)"
	tp=$(devtype "$devname")
	echo "$tp"
}

get_mkinitrd_com() {	# build the command line to run the initrd builder
	check_initrd	# get mkinitrd name
	if [ "$MKINITRD" == "mkinitcpio" ]; then	# Arch Linux
		initrd_mkinitcpio
	elif [ "$MKINITRD" == "dracut" ]; then
		initrd_dracut
	elif [ "$MKINITRD" == "update-initramfs" ]; then
		initrd_update_initramfs
	elif [ "$MKINITRD" == "mkinitramfs" ]; then
		initrd_mkinitramfs
	elif [ "$MKINITRD" == "mkinitrd" ]; then
		initrd_mkinitrd
	elif [ "$MKINITRD" == "genkernel" ]; then
		initrd_genkernel
	fi
	if [ -z "$MKINITRD" ]; then
		return 1
	else
#		printing "Initramfs generator: ${cB}${MKINITRD}${cEnd}"
		echoing "Initramfs generator: ${cB}${MKINITRD}${cEnd}"
		logging "Initramfs generator: ${MKINITRD}"
		printing "Initramfs generator command: \"$COM_MKINITRD\" "
	fi
	echo -e "COM_MKINITRD=\"$COM_MKINITRD\"" >> $VARSFILE
}

get_mountpoint_fstab_nametype() {	# get type of device from mountpoint name

	# e.g.: get_mountpoint_fstab_nametype /boot
	mp=$1
	if [ "$mp" == "swap" ]; then
		# swap in fstab may have no mountpoint. Use fstype field instead to check it
		dv=$(awk -v mp="$mp" '!/^[ \t]+$/ && !/^[ \t]*#/ && $3 == mp {print $1}' $FSTAB)
	else
		dv=$(awk -v mp="$mp" '!/^[ \t]+$/ && !/^[ \t]*#/ && $2 == mp {print $1}' $FSTAB)
	fi
	tp1=$(devtype "$dv")
	echo "$tp1"
}

get_system_disk() {				# parse the system disk 
	local rootname=$(get_system_partition)
	local sdisk=$(echo "$rootname" | sed s'/[0-9]*//'g)
	echo $sdisk
}

get_system_partition() {		# get the system partition name
	rootname=$(mount | grep ^/dev | awk '$3 == "/" {print $1}')
	local rn=$(lvm2dev "$rootname")
	if [ -n "${rn}" ]; then
		rootdisk=${rn}
	else
		rootdisk=$(realdev $rootname)
	fi
	logging "$rootdisk is the root (/) partition"
	echo "$rootdisk"
	return
}

get_utils_versions() {		# get version number of critical utilities
	# get version numbers of kernel, mdadm, bash
	KERNEL_VERSION=$(uname -r | sed 's/-.*$//')
	BASH_VERSION="${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}"
	MDADM_VERSION=$(mdadm --version 2>&1 | cut -d'-' -f2 | sed 's/[ v]//g')
	PARTED_VERSION=$(parted --version | head -n1 | awk '{print $NF}')
}

human_value() {			# change size in bytes to human value (Gb, Mb, etc.)
	local sz=$1
	if [ $sz -lt 1000 ]; then
		val=1000
		unit="B"
	elif [ $sz -lt $(( 1000*1000 )) ]; then
		val=$(( 1000*1000 ))
		unit="K"
	elif [ $sz -lt $(( 1000*1000*1000 )) ]; then
		val=$(( 1000*1000*1000 ))
		unit="M"
	elif [ $sz -lt $(( 1000*1000*1000*1000 )) ]; then
		val=$(( 1000*1000*1000*1000 ))
		unit="G"
	elif [ $sz -lt $(( 1000*1000*1000*1000*1000 )) ]; then
		val=$(( 1000*1000*1000*1000*1000 ))
		unit="T"
	fi
	echo "$(( ($sz*1000)/($val) ))$unit"
}


initrd_dracut(){	# mkinitrd for RedHat centric distros (Fedora, RedHat, Centos, Mandrake)
	opt="--mdadmconf --force"	
	if (dracut --help | grep -q '\-\-fstab'); then	# some earlier dracut versions don't have fstab option
		opt="$opt --fstab"
	fi
	if [ -z "${vInitrd}" ]; then
		COM_MKINITRD="dracut ${opt}"
	else
		initrd_img="$(basename $(echo "${vInitrd}" | cut -d'/' -f2-))"	# get initrd.img name, removing other info in the line
		COM_MKINITRD="dracut ${opt} /boot/${initrd_img}"
	fi
}

initrd_genkernel() {	# mkinitrd for gentoo centric distros (not implemented yet)
	local opt=""
	# check if lvm is needed
	if parted_machine ${DISK[0]} | awk -F: '{print $7}' | grep -q lvm ; then
		opt="--lvm "	# if there is a lvm partition, we need to load lvm module in initramfs
	fi
	opt="${opt}--mdadm --mdadm-config=/etc/mdadm.conf"   ## FIXME we don't know yet where it is MDADM_CONF
	COM_MKINITRD="genkernel $opt initramfs"
	if [ -z "$vInitrd" ]; then	# if there is no initramfs in grub we need to create one
		local arch=$(uname -m)
		case "$arch" in
			i?86)
				arch="x86"
				;;
			mips|ps|mips64)
				arch="mips"
				;;
			arm*)
				arch="arm"
				;;
			*)
				;;
		esac
		local suf
		if check_support_bootp ; then	# check if there will be a /boot partition
			suf="/"
		else
			suf="/boot/"
		fi
		vInitrd="${suf}initramfs-genkernel-$arch-$(uname -r)"
	fi
}

initrd_mkinitcpio() {		# build the mkinitcpio command line for arch linux
	# prepare hooks
	"cp" -pf ${MKINITCPIO_CONF} ${NEW_MKINITCPIO}
	local NEW_HOOKS=""
	local hook
	local roottype
	local HOOKS=$(grep ^HOOKS= ${MKINITCPIO_CONF} | sed -e s'/HOOKS=//'g -e s'/\"//'g)

	for r in $(cat /proc/cmdline); do 
		if (echo $r | grep -q ^root= ); then
			roottype=$(devtype $(echo $r | sed 's/^root=\(.*\)/\1/g'))
			break
		fi
	done
	if [ "$roottype" == "dev" -o "$roottype" == "LABEL" -o "$roottype" == "mapper" ]; then
		hook="mdadm"
	elif [ "$roottype" == "UUID" -o "${roottype:0:3}" == "by-" ]; then
		hook="mdadm_udev"
	else
		fatal_error "Root partition type undefined:"
		exit 1
	fi
	for i in $(echo "${HOOKS}" | sed s'/ /\n/'g | tac)
	do
		if (echo "autodetect sata scsi pata" | grep -q " $i "); then
			NEW_HOOKS=$(echo "${HOOKS}" | sed s"/$i/$i $hook/"g)	# include "mdadm_udev" after all hooks described in the line above
			break
		fi
	done
	sed -i.tmp s"/$HOOKS/$NEW_HOOKS/"g $NEW_MKINITCPIO
	"rm" -f $NEW_MKINITCPIO.tmp	
	local a=0
	for i in $(grep -R ${vInitrd} /etc/mkinitcpio.d | cut -d':' -f1 | grep -v example)
	do
		KERNEL_PRESET=$(basename $i | sed 's/\.preset//g')
		a=$((a+1))
	done
	if [ $a -ne 1 ]; then
		# No preset? More then one preset? Something is wrong
		# create the command without preset, using image in grub initrd
		COM_MKINITRD="mkinitcpio -g ${vInitrd}"
	else
		COM_MKINITRD="mkinitcpio -p $KERNEL_PRESET"
	fi
}


initrd_mkinitramfs() {	# mkinitrd for older distros
		COM_MKINITRD="mkinitramfs -k -o ${vInitrd} $(uname -r)"
}


initrd_mkinitrd() {		# mkinitrd for Opensuse, Mandriva 2010, Slackware, Older RedHat centric
		if (echo "$DISTRO" | grep -q -i "opensuse"); then	# opensuse don't need other options
			COM_MKINITRD="mkinitrd"
		### check if distro is slackware, because options are different
#		elif (echo "$DISTRO" | grep -q -i "slackware"); then
		elif [ -f /usr/share/mkinitrd/mkinitrd_command_generator.sh ]; then
		# slackware centric distros using mkinitrd use this script
			# get keymap
			local kmap=""
			if [ -f /etc/rc.d/rc.keymap ]; then
				kmap=$(grep -v "^#" /etc/rc.d/rc.keymap | grep "\.map" | grep loadkeys | awk '{print $2}')
				if [ -n "$kmap" ]; then
					kmap="-a \"-l ${kmap}\""
				fi
			fi
			
			if [ $BOOTP_MODE -eq 1 ]; then
				local temp_DISK_DB=$DISK_DB_VIRTUAL
			else
				local temp_DISK_DB=$DISK_DB
			fi
			local mdN=$(awk '$6=="/" {print $7}' $temp_DISK_DB)
			local rfs
			if [ $mdN -ge 0 ]; then
				rfs='\-r \/dev\/md'${mdN}
				#rfs=$(echo "$rfs" | sed -e 's/\//\\\//g' -e 's/\-/\\\-/g')
			else
				fatal_error "Rootfilesystem must be a raid array"
				exit 1
			fi

			if [ -x /usr/share/mkinitrd/mkinitrd_command_generator.sh ]; then
				COM_MKINITRD="/usr/share/mkinitrd/mkinitrd_command_generator.sh $kmap --run"				
			else
				### I think this block code is not needed. Is it(??)
				COM_MKINITRD="mkinitrd -c -k $(uname -r) -f $(awk '$6=="/" {print $4}' $temp_DISK_DB) ${kmap} -r $rfs -u -R -o /boot/initrd.gz"
			fi
		else	# older redhat, mandriva, mageia, centos use mkinitrd with these options
			local preload1=""
			echo "456" | grep -q "${RAID_TYPE}"
			if [ $? -eq 0 ]; then
				preload1="--preload=raid456 "
			elif [ "${RAID_TYPE}" == "10" ]; then
				preload1="--preload=raid10 "
			fi		
			COM_MKINITRD="mkinitrd -f --preload=raid1 ${preload1}${vInitrd} $(uname -r)"
		fi
}


initrd_update_initramfs() {	# mkinitrd for Ubuntu centric distros, Debian, Linux Mint
	MKINITRD="mkinitramfs"
	COM_MKINITRD="update-initramfs -u"
}


kernel_messages_on() {		# unblock kernel messages to the terminal
	if [ -e /tmp/printk-$$ ]; then
		cat /tmp/printk-$$ > /proc/sys/kernel/printk
		"rm" -f /tmp/printk-$$
	fi
}

kernel_messages_off() {		# block kernel messages to the terminal to avoid messing the display
	cat /proc/sys/kernel/printk > /tmp/printk-$$
	echo 0 > /proc/sys/kernel/printk
}

lformat_bootflag() {	# parse partition boot flag 
	local disk=$1
	local np=$2
	local fl=$(parted_machine ${disk} 2>/dev/null | awk -F: -v np=$np '$1==np {print $7}' | grep boot)
	if [ -n "$fl" ]; then
		echo "*boot"
	else
		echo "-"
	fi
}

lformat_dos_type() {	# parse partition msdos type 
	local infop=$1
	local tp=$(echo "$infop" | awk '{print $5}' | sed 's/[a-z]/\u&/')
	if [ -z "${tp}" ]; then
		tp=" "
	fi
	echo "${tp:0:3}"
}

lformat_gpt_name_partition() {	# parse partition name (only in gpt partitions)
	local disk=$1
	local np=$2
	local nm=$(env LC_ALL=C parted -m $disk p | awk -F: -v np=$np '$1==np {print $6}')
	if [ -z "${nm}" ]; then
		nm="-"
	fi
	echo "${nm}"
}

lformat_sys_type() {	# parse system type partitions 
	local disk=$1
	local device=$2
	local np=$3
	if [ $(ptable_type $disk) == "MBR/msdos" ]; then
		local id=$(env LC_ALL=C sfdisk -d $disk 2>/dev/null | awk -v dv="^$device" -F, '$1 ~ dv {print $3}' | awk -F= '{print $2}' | sed 's/ //g')
		local systype=$(env LC_ALL=C sfdisk -T | awk -v id=$id '$1==id' | sed 's/^.\{4\}//')
		echo -e "${systype}"
		return 
	fi
	systype=$(parted_machine $disk | awk -F: -v np=$np '$1==np {print $7}' | sed 's/;$//g')
	echo -e "${systype}"
}

mount_clean() {		# Create a file named mount_clean, that has only the device and mountpoint needed to raider
	# the device is referenced in /proc/partitions

	# MOUNT_CLEAN.tmp = $FSTAB with only physical mountpoint partitions 
	# MOUNT_CLEAN.FSTAB = $FSTAB with the real device partition including swap (/proc/partition device) in the first field
	#	and the original device in the last field
	# MOUNT_CLEAN = ordered MOUNT_CLEAN_FSTAB without swap. Usefull when we need later to mount chroot in the right order


	local MOUNT_CLEAN1=$MOUNT_CLEAN.tmp
	local CLEAN_FSTAB=$MOUNT_CLEAN.FSTAB
	grep -e ^"/dev" -e ^"UUID=" -e ^"LABEL=" $FSTAB > $MOUNT_CLEAN1	# fstab with only partition mountpoints 
	>$CLEAN_FSTAB
	>$MOUNT_CLEAN
	# read physical mountpoints from FSTAB
	while read mnt1
	do
		dev=$(echo "$mnt1" | awk '{print $1}')	# device name as written in FSTAB
		devA=$(realdev $dev)					# real device as it's written in /proc/partitions
		mpoint=$(echo "$mnt1" | awk '{print $2}')	# mountpoint related to device
		parttype=$(echo "$mnt1" | awk '{print $3}')	# partition type or filesystem
		if ! [ -z "$devA" ]; then
			# only consider devices detected
			echo "$devA $mpoint $parttype $dev" >> $CLEAN_FSTAB	# fstab cleaned + original device in the last field
		fi
	done < $MOUNT_CLEAN1

	# fix the mount order
	for m in $(mount | awk '/^\/dev/ {print $3}')
	do
		awk -v mt="$m" '$2 == mt {print}' $CLEAN_FSTAB >> $MOUNT_CLEAN	# ordered mount cleaned
	done
}

mount_clean_virtual() {		# The same as mount_clean but used in BOOTP_MODE
	# this is done after creating NEWFSTAB
	# it is based in NEWFSTAB that was created with /boot partition 
	local MOUNT_CLEAN2=$MOUNT_CLEAN.tmp
	local CLEAN_FSTAB=$MOUNT_CLEAN.FSTAB
	grep -e ^"/dev" -e ^"UUID=" -e ^"LABEL=" $NEWFSTAB > $MOUNT_CLEAN2	# NEWFSTAB with only partition mountpoints 
	>$CLEAN_FSTAB
	>$MOUNT_CLEAN_VIRTUAL
	while read mnt2
	do
		local dev=$(echo "$mnt2" | awk '{print $1}')	# device name as written in FSTAB
		local devA=$(realdev $dev)						# real device as it's written in /proc/partitions
		local mpoint=$(echo "$mnt2" | awk '{print $2}')	# mountpoint related to device
		local parttype=$(echo "$mnt2" | awk '{print $3}')	# partition type or filesystem
		if ! [ -z "$devA" ]; then
			# only consider devices detected
			echo "$devA $mpoint $parttype $dev" >> $CLEAN_FSTAB	# fstab cleaned
		fi
	done < $MOUNT_CLEAN2

	# fix the mount order
	# first is "/" then "/xxx" "/xxx/yyy"
	"cp" ${CLEAN_FSTAB} ${MOUNT_CLEAN_VIRTUAL}
	max=$(cat $MOUNT_CLEAN_VIRTUAL | wc -l)
	for ((a=max; a>0 ; a--))
	do
		max1=$a
		for (( i=1; i<max1; i++))
		do
			i1=$((i+1))
			ln=$(awk -v n=$i 'NR==n {print}' $MOUNT_CLEAN_VIRTUAL)
			ln1=$(awk -v n=${i1} 'NR==n {print}' $MOUNT_CLEAN_VIRTUAL)
			dev=$(echo $ln | awk '{print $2}')
			dev1=$(echo $ln1 | awk '{print $2}')
			nsl="${dev//[^\/]/}"
			lev=${#nsl}
			nsl="${dev1//[^\/]/}"
			lev1=${#nsl}
			# tests
			if [ "$dev1" == "/" ]; then	# "/" must be always de first
				swapl
			elif [ $lev1 -lt $lev ]; then	# first highest level directories (lower numbers)
				swapl
			fi
		done
	done
}

need_runlevel_1() {	# check if this distro need runlevel 1 to run raider
	# check if this distro need runlevel 1 to run raider
	echo $DISTRO | grep -qi -e "mageia" -e "mandriva linux release 2010"
	if [ $? -eq 0 ]; then
		return 0
	fi
	return 1
}

parse_bp_arg () {	# parse values form --boot option
	local value=$1

	if [ "$value" == "noboot" ]; then
		return 2
	fi
	for i in ext2 ext3 ext4 xfs reiserfs jfs
	do
		if [ "$value" == "$i" ]; then
			BOOTP_FS=$i
			return 0
		fi
	done
	value=$(echo $value | sed 's/[a-z]/\u&/')	# upper
	unit_value=$(parse_value_type ${value})
	local found=0
	for i in M MB K KB	# only allow Mbytes or Kbytes
	do
		if [ "$unit_value" == "$i" ]; then
			local v=$(remove_value_type $value)
			v=${v:=0}
			if [ $v -eq 0 ]; then
				return 1
			fi
			BOOTP_SIZE=$value
			return 0
		fi
	done
	return 1
}

parted_machine() {	# alternative "parted -m" for oldest version < 1.8.3
	# it prints enough information but not all
	# e.g.: parted_machine /dev/sdb u MB
	
	local dev=$1
	local u=$2
	local v=$3

	if (check_utils_versions $PARTED_VERSION 1.8.3); then
		# if parted does have "-m" option 
		env LC_ALL=C parted -s -m ${dev} $u $v print 
		return
	fi
	# if parted does not have "-m" option
	local PARTED=$TEMP/parted_all
	local PMCH=$TEMP/parted_machine

	env LC_ALL=C parted -s ${dev} $u $v print  > $PARTED
	cat $PARTED | awk '$1=="Number"' > $PMCH
	cat $PARTED | awk '$1 ~ "[0-9]+"' >> $PMCH
	ff=$(head -n1 $PMCH | sed 's/ /\\0040/g')
	local f1=2
	local f2=$(echo -e ${ff} | awk '{print index($0, "Start")}')
	local f3=$(echo -e ${ff} | awk '{print index($0, "End")}')
	local f4=$(echo -e ${ff} | awk '{print index($0, "Size")}')
	local f5=$(echo -e ${ff} | awk '{print index($0, "Type")}')
	local f6=$(echo -e ${ff} | awk '{print index($0, "File system")}')
	local f7=$(echo -e ${ff} | awk '{print index($0, "Flags")}')
	
	local DISK_SIZE=$(awk 'BEGIN {FS=":"} $1 ~ "^Disk" {print $2}' $PARTED)
	local HDEVICE=$(grep ^Model $PARTED | sed 's/.*(\(.*\))$/\1/g')
	local MODEL=$(grep ^Model $PARTED | sed -e 's/^Model: \(.*\)(.*$/\1/g' -e 's/ $//')
	local PTABLE=$(awk 'BEGIN {FS=":"} /^Partition Table/ {print $2}' $PARTED)
	echo "BYT;"
	echo "$(echo "${dev}:${DISK_SIZE}:${HDEVICE}:::${PTABLE}" | sed 's/ //g'):${MODEL};"
	local  pc=$(cat $PMCH | wc -l)
	for ((n=1; n<pc ; n++ ))
	do
		aa=$(awk -v p=${n} 'NR==p' <(tail -n+2 $PMCH) | sed 's/ /\\0040/g' )
		a1=$(echo -e ${aa} | cut -c${f1}-$((f2-2)))
		a2=$(echo -e ${aa} | cut -c${f2}-$((f3-2)))
		a3=$(echo -e ${aa} | cut -c${f3}-$((f4-2)))
		a4=$(echo -e ${aa} | cut -c${f4}-$((f5-2)))
		a6=$(echo -e ${aa} | cut -c${f6}-$((f7-2)))
		a7=$(echo -e ${aa} | cut -c${f7}-)
		b=$(echo "${a1}:${a2}:${a3}:${a4}:${a6}::${a7};" | sed -e 's/ //g' -e 's/,/, /g')
		echo $b
	done
	"rm" -f $PMCH
	"rm" -f $PARTED
}

reconfig_config_files() {	# change new config files before copying to chroot directory
	# reconfig fstab
	# loop NEWFSTAB
	# 
	local dev
	local mp
	local fs
	local typeofdev
	local new_dev
	local temp_DISK_DB

	if [ $BOOTP_MODE -eq 1 ]; then
		temp_DISK_DB=$DISK_DB_VIRTUAL
	else
		temp_DISK_DB=$DISK_DB
	fi
	>$NEWFSTAB.tmp
	printing "Fix name devices in config files, if udev names are used"
	printing "Fixing name devices in $FSTAB"
	
	local fixed_fstab="no"
	while read tabl
	do
		if (echo "$tabl" | grep -q -e ^/dev -e ^"UUID=" -e ^"LABEL=" ); then
			if (echo "$tabl" | grep -q -e ^/dev/md[0-9]* -e ^/dev/[hs]d.*); then	
				dev=$(echo "$tabl" | awk '{print $1}')
				mp=$(echo "$tabl" | awk '{print $2}')
				fs=$(echo "$tabl" | awk '{print $3}')
				local Ndisk
				for (( u=0; u<=LASTDISK; u++ ))
				do
					echo "$dev" | grep -q ^${DISK[$u]}
					if [ $? -eq 0 ]; then
						Ndisk=$u
					fi
				done
				if [ "$fs" == "swap" ]; then
					if [ -f $SWAP_NEED_FORMAT ]; then	# when there is a second swap partition
						# This is a little confusing, but it seems the right way to do it...
						# Check if swap belongs to disk[last], then the type must be "dev" (not uuid, or others)
						# (Only in step 3 it will be formatted , get the uuid, and fix the fstab name)
						# If swap belongs to disk[0], and type is different from "dev", 
						# get the name based in swap from disk[0+1] (not in disk[0])
						# If swap belongs to other disks get the name based in disk[x+1]
						echo $dev | grep -q ${DISK[${LASTDISK}]}
						if [ $? -eq 0 ]; then
							typeofdev="dev"
						else
							typeofdev=$(awk -v fs="$fs" '$4 == fs {print $8}' $temp_DISK_DB)
							if [ "$typeofdev" != "dev" ]; then
								for (( u=0; u<=LASTDISK; u++ ))
								do
									echo "$dev" | grep -q ^${DISK[$u]}
									if [ $? -eq 0 ]; then
										Ndisk=$u	# get the "number" of the disk in $DISK[]
										break
									fi
								done				
								Ndisk=$(( Ndisk+1 ))	# get the uuid/LABEL/... from the next disk in the order
								dev="${DISK[${Ndisk}]}$(cat $SWAP_NEED_FORMAT)"
							fi
						fi
					else
						typeofdev=$(awk -v fs="$fs" '$4 == fs {print $8}' $temp_DISK_DB)
					fi
				else
					if [ "$mp" == "/boot/efi" ]; then
						typeofdev="dev"	
					else
						typeofdev=$(awk -v mp="$mp" '$6 == mp {print $8}' $temp_DISK_DB)
					fi
				fi
				new_dev=$(dev2devtype "$dev" "$typeofdev")
				if [ -z "$new_dev" ]; then
					new_dev=$dev	# if the device don't have the devicetype we want, get the original devicename
				fi 
				echo "$tabl" | awk -v new_dev="$new_dev" '$1 = new_dev {print}' >> $NEWFSTAB.tmp
				if [ "$new_dev" != "$dev" ]; then
					fixed_fstab="yes"
				fi
				continue
			fi
		fi
		echo "$tabl" >> $NEWFSTAB.tmp
	done < $NEWFSTAB
	"mv" -f $NEWFSTAB.tmp $NEWFSTAB

	if [ "$fixed_fstab" == "yes" ]; then
		printfile "New FSTAB after renaming the devices to the original types:" $NEWFSTAB
	else
		printing "... not need to fix names. Nothing done."
	fi
		
	# reconfig grub.conf only in grub 1
	# change ROOT_FS_MD to ROOT_FS_MD with original type in grub1 config file
	if [ "${GRUBNAME}" == "1" ]; then
		typeofdev=$(awk '$6 == "/" {print $9}' ${temp_DISK_DB})
		local rfs=$(dev2devtype ${ROOT_FS_MD} ${typeofdev})
		if [ -z "$rfs" ]; then
			rfs="${ROOT_FS_MD}"
		fi
		if [ "${ROOT_FS_MD}" != "${rfs}" ]; then	# only change if it is not the same
			printing "Fixing name devices in $MENULST"
			slash_ROOT_FS_MD=$(echo ${ROOT_FS_MD} | sed s'/\//\\\//'g)
			slash_rfs=$(echo ${rfs} | sed s'/\//\\\//'g)
			sed -i.tmp "s/$slash_ROOT_FS_MD/$slash_rfs/g" ${NEWMENULST_MD}
			"rm" -f ${NEWMENULST_MD}.tmp

			# change resume= if it exists and --no-swapraider=0
			if [ -n "$vResume" ] && [ $NO_SWAPRAIDER -eq 0 ]; then
				devresume="$(grep -m 1 ^[[:blank:]]*kernel ${NEWMENULST_MD} | sed -e 's/.*resume=//g' -e 's/ .*//g')"
				newresume="$(dev2devtype ${devresume} ${typeofdev})"
				printing "Changing resume=${devresume} to resume=${newresume} "
				slash_devresume="$(echo $devresume | sed 's/\//\\\//g')"
				slash_newresume="$(echo $newresume | sed 's/\//\\\//g')"
				sed -i.tmp "s/resume=$slash_devresume/resume=$slash_newresume/g" ${NEWMENULST_MD}
				"rm" -f ${NEWMENULST_MD}.tmp
			fi
			printfile "New $(basename ${NEWMENULST_MD}) after renaming the devices to the original types:" ${NEWMENULST_MD}
			
		fi
	fi
}

repeatchar() {	# repeat character n times
	# e.g.: repeatchar "-" 20  
	# --------------------
	local ch=$1
	local num=$2
	local str=""
	for ((i=1; i<=${num}; i++))
	do str="${str}${ch}"; done
	echo "${str}"
}

revision_number() {	# print raider revision number
	echo $RAIDER_REV
}

rpad() {		# right pad string with N whitespaces
	# e.g.: # rpad "string" 20
	local str=$1
	local num=$2
	if [ $# -lt 2 ]; then
		num=${str}
		str=" "
	fi
	str=${str:0:${num}}
	sp=$(spaces ${num})
	echo "${str}${sp:${#str}}"
}

save_disks_step3() {	# save which disks step3 will need to work on
	# save "raided" disks. 
	# save all disks but the first
	# because in step 3, only the raided disks are needed
	>${DISKS_STEP3}
	for ((n=1; n <= LASTDISK; n++))
	do
		echo "${DISK[$n-1]} $(d_info_model ${DISK[$n]})--$(d_info_serial ${DISK[$n]})" >> ${DISKS_STEP3}
	done
}


set_selinux() {		# check if selinux enabled and set autorelabel		

	if (check_selinux); then
		printing "Set selinux to relabel all system"
		touch "${MOUNTPOINT}/.autorelabel"
	fi
}

set_step() {			# save step number
	STEP=$1
	echo $STEP > $STEP_FILE
}

set_to_step1_raider_dir() {		# In step 2, set global variables with values from step 1 
	fill_tempfiles_variables
}

spaces() {		# print a string with N spaces
	# e.g.: # spaces 20
	local ns=$1
	local str=""
	for ((i=1; i<=${ns}; i++))
	do str="${str} "; done
	echo "${str}"
}

speed_test() {	# test disk speed
	hdparm --direct -t ${DISK[0]} | tail -n1 | awk '{print $(NF-1)}'
}

step_scan() {			# Scan raider step 
	# checked step when running --run option
	if [ -f "$STEP_FILE" ]; then
		STEP=$( head -n1 $STEP_FILE )
		if [ $STEP -eq 2 ]; then
			fill_tempfiles_variables
		fi
	else
		STEP=99	# no stepfile
	fi
}

swapl() {	# swap lines in mount_clean (this is part of mount_clean_virtual function)
	sed -i.tmp "${i} d" $MOUNT_CLEAN_VIRTUAL
	rm -f ${MOUNT_CLEAN_VIRTUAL}.tmp
	sed -i.tmp "${i}a\
	${ln}" $MOUNT_CLEAN_VIRTUAL
	rm -f ${MOUNT_CLEAN_VIRTUAL}.tmp
}

total_disk_space_used() {	# total system disk space used in kB
	df -kP | grep ^/dev | awk '{sum+=$3} END {print sum}'
}

umount_chroot() {		# unmount chroot system
	umounter ${MOUNTPOINT}/sys
	umounter ${MOUNTPOINT}/dev
	umounter ${MOUNTPOINT}/proc
	tac $TEMP/chroot_mtab > $TEMP/chroot_mtab1	# change the order of devices to unmount chroot.
	while read p
	do
		umounter $(echo $p | awk '{print $1}')
	done < $TEMP/chroot_mtab1
}


umounter() {	# unmount mount point
# e.g.: umounter $mpoint
local mpoint=$1
local n=0
until (umount $mpoint)
do
	((n++))
	if [ $n -gt 3 ]; then
		umount -l $mpoint
		break
	fi
	sleep 1
done
}


version_info() {	# Display program name, version and revision
	# Prints information about version number
	echo "${PROGRAM_NAME} - Version $VERSION  (Rev: $RAIDER_REV)"
}

version_number() {	# Display version number only
	echo ${VERSION}
}
