#!/bin/bash
#
# step2 
# This file is part of Raider

go_step_2() {	# run step 2
	if [ "${FUNCNAME[1]}" != "single_to_raid1" ] && [ "${FUNCNAME[1]}" != "single_to_raid5" ]; then
		source $VARSFILE
	fi
	>$TEMP/temp_mountpoints
	>$TEMP/chroot_mtab
	>$TEMP/chroot_mtab1

	logdivision
	date +%F" "%T >> $LOGFILE
	local RAID_TYPE
	case ${MAIN_COMMAND} in
		R1) optmessage="Option: Single disk to RAID 1 (MIRRORING)"
			;;
		R4) optmessage="Option: Single disk to RAID 4"
			;;			
		R5) optmessage="Option: Single disk to RAID 5"
			;;
		R6) optmessage="Option: Single disk to RAID 6"
			;;
		R10) optmessage="Option: Single disk to RAID 10"
			;;
	esac
	RAID_TYPE=$(echo ${MAIN_COMMAND} | sed 's/R//g')
	if [ ${TEST_MODE} -eq 1 ]; then
		printing "$PROGRAM_NAME version $VERSION started"
		echoing "$optmessage"
		printdivision
	fi
	
	local type_asking=0
	if (check_runlevel_S); then
		printing "Running in \"single mode\""
		if (avoid_runlevel_1); then
			fatal_error "$DISTRO is not able to run raider in \"single\" mode"
			echoing "Please change to multiuser mode"
			exit 1
		fi
		echoing "Good!..."
	else
		type_asking=1
		echoing "You are not running in \"single mode\""
		if (avoid_runlevel_1); then
			echoing "This is ok for ${DISTRO}. Good..."
			type_asking=0

#		else
#			echoing "Although not mandatory, it is advisable to run raider"
#			echoing "in \"single mode\" (read the README file)"			
		fi
	fi
	printdivision

	newdisks=""

	for (( i=1; i < ${#DISK[@]}; i++))
	do
		newdisks="${newdisks}${DISK[$i]} "
	done
	echo " :: Please wait..."	
	echo -ne "\r\033[1A"
	
	# A inaccurate prediction time
	local sdu="$(total_disk_space_used)"	# Kb
	local sduM=$(echo $sdu/1000|bc)		# disk space to transfer in Mb
	local secdu=$(convert_Kbytes2sectors $sdu ${DISK[0]})
	local sduH=$(convert_sectors2Human $secdu ${DISK[0]})	# disk space in Human units
	printing "BuildRaid phase will start now!"
	printing "There are ${sduH} of data to be copied to the new raid system"

	speedpreview=$(echo "4-(0.5*(${#DISK[@]}-1))"|bc)
	timepreview=$(echo "$sduM/$speedpreview"|bc)	# seconds
	tp=$(echo $timepreview/60|bc)	# convert to minutes
	if [ $tp -le 60 ]; then
		prediction="several minutes to one hour(?)"
		predlog="$tp minutes"
	elif [ $tp -gt 60 -a $tp -lt 1440 ]; then
		prediction="several hours(?)"
		predlog="$timepreview hours"
	else
		prediction="more then one day(?)"
		predlog="$timepreview hours"
 	fi
 	printing "BuildRaid phase will take a long time, maybe ${prediction}."
	logging "A very inaccurate prediction time: $predlog"
	printdivision
	
	if [ $type_asking -eq 1 ]; then
		echoing_n "Do you want to continue without changing to \"single mode\"? (y/[n])"
	else
		echoing_n "Do you want to continue? (y/[n])"
	fi
	read cnt1
	if ! [ "$cnt1" == "y" -o "$cnt1" == "Y" ]; then
		echoing "Aborted!"
		if [ $type_asking -eq 1 ]; then
			echoing "Change to \"single mode\" and then enter \"raider --run\""
		fi
		exit 1
	fi

	printing "BuildRaid phase started..."
	logdivision
	SECONDS=0
	printing "Working on $newdisks..."
	printdivision
	kernel_messages_off
	sleep .5
	
	## If raid modules are not compiled in kernel
	## load raid456 module
	## load raid10
	## always load raid1 if it not loaded yet
	if ! (check_kernel_raid_drivers); then
		echo "456" | grep -q "$RAID_TYPE" 
		if [ $? -eq 0 ]; then
			RAIDMOD="raid456"
		else
			RAIDMOD="raid${RAID_TYPE}"
		fi
		if ! (lsmod | grep 'raid1 ' 2>&1 >/dev/null); then	# raid 1 is almost always needed too 
															# (grub1 needs raid 1 for all raid modes to be able to boot)
			logging "Module raid1 not loaded yet"
			modprobe raid1
			if [ $? -ne 0 ]; then	
				fatal_error "Module raid1 not found"
				printing "and raid1 driver not built in the kernel too!"
				printing "Kernel must be recompiled with raid options selected"
				kernel_messages_on
				exit 1
			else
				logging "Module raid1 successfully loaded"
			fi
		fi
		if [ "$RAID_TYPE" != "1" ]; then
			if ! (lsmod | grep "raid${RAID_TYPE}" 2>&1 >/dev/null); then
				logging "Module ${RAIDMOD} not loaded yet"
				modprobe ${RAIDMOD}
				if [ $? -ne 0 ]; then
					fatal_error "Module ${RAIDMOD} not found"
					printing "and ${RAIDMOD} driver not built in the kernel too!"
					#printing "Kernel must be recompiled with raid options selected"
					kernel_messages_on
					exit 1				
				fi
				if ! (lsmod | grep ${RAIDMOD} 2>&1 >/dev/null); then
					fatal_error "Module ${RAIDMOD} was not able to be loaded"
					kernel_messages_on
					exit 1
				else
					logging "Module ${RAIDMOD} successfully loaded"
				fi
			else
				logging "Module ${RAIDMOD} already loaded"
			fi
		fi
	fi
	
	#### Copy partition to new disk
	printing "Copying partitions from disk ${DISK[0]} to ${newdisks}"
	
	for (( h=1; h < ${#DISK[@]}; h++))	# partition all new disks
	do	
		# clone if gpt partition
		clone_gpt_partition ${DISK[$h]}
		res=$?
		if [ $res -eq 1 ]; then	# clone as a mbr partition
			pt_part="msdos"
			if [ $BOOTP_MODE -eq 1 ]; then
				part_copy_from_disk_virt ${DISK[$h]}
			else
				sfdisk -d ${DISK[0]} 2>/dev/null | sfdisk -f ${DISK[$h]} 2>$TEMP/sfd >/dev/null
			fi
		elif [ $res -eq 2 ]; then		# exit if disk in use
			printing "Disk $DISK[$h] is currently in use"
			return 1
		else
			pt_part="gpt"
		fi
	done

	>${ADDERARRAY}
	local temp_DISK_DB
	if [ $BOOTP_MODE -eq 1 ]; then
		temp_DISK_DB=$DISK_DB_VIRTUAL
	else
		temp_DISK_DB=$DISK_DB
	fi
	local raid_type_exception
	while read dbinfo
	do
		npart=$(echo $dbinfo | awk '{print $1}')	# partition number
		nraid=$(echo $dbinfo | awk '{print $7}')	# number raid array "mdX"
		if [ $nraid -ge 0 ]; then
			
			printing "Configure partitions"
		for (( h=1; h < ${#DISK[@]}; h++))
		do
			if [ "$pt_part" == "msdos" ]; then
				logging "Change ${DISK[$h]}${npart} partition to \"linux raid autodetection\""
				sfdisk --change-id ${DISK[$h]} $npart fd >>$LOGFILE 2>&1
			else
				logging "Change ${DISK[$h]}${npart} partition to \"raid\""
				env LC_ALL=C parted ${DISK[$h]} set $npart raid on >>$LOGFILE 2>&1
			fi
		done	
			# check if "npart" partition is where the /boot directory resides
			# if boot_partition="yes" then create mdarray with metadata=0.90 when using grub 1 and grub 2 < 1.99
			boot_partition="no"
			if [ "$(awk -v npart="$npart" '$1 == npart {print $6}' $temp_DISK_DB)" == "/boot" ]; then
				boot_partition="yes"
			elif [ "$(awk -v npart="$npart" '$1 == npart {print $6}' $temp_DISK_DB)" == "/" ]; then
				if [ -z "$(awk '$6 == "/boot" {print}' $temp_DISK_DB)" ]; then
					boot_partition="yes"	# if npart == "/" and there is no /boot partition, then mark this "yes"
				fi
			fi

			# /boot partition is always Raid 1 if BOOTRAID1_MODE is 1
			raid_type_exception=${RAID_TYPE}
			if [ "$(echo $dbinfo | awk '{print $6}')" == "/boot" ]; then
				if [ $BOOTRAID1_MODE -eq 1 ]; then
					raid_type_exception=1
				fi
			fi
		
			create_mdarray ${nraid} ${npart} ${raid_type_exception} ${boot_partition}
			rtv=$?
			if (ls /dev/md${nraid} >/dev/null 2>&1 ); then
				if [ $rtv -ne 0 ]; then
					fatal_error "Raid array /dev/md${nraid} not created"
					exit 1
				else
					logging "Add /dev/md${nraid} to ADDERARRAY"
				fi
				echo /dev/md${nraid} ${npart} >> $ADDERARRAY
			else
				fatal_error "/dev/md${nraid} raid array, failed to be created!"
				exit 1
			fi
		fi
	done < $temp_DISK_DB
	printfile "ADDERARRAY file created:" ${ADDERARRAY}
	save_disks_step3
	printfile "Saved disks needed to run step 3" $DISKS_STEP3
	
	# create mountpoint directory
	if ! [ -d "$MOUNTPOINT" ]; then
		if ! (mkdir -p $MOUNTPOINT); then
			fatal_error "Unable to create $MOUNTPOINT directory "
			exit 1
		fi
	fi
	
	# Formating new raid arrays and partitions in new disk 
	while read dbdisk1
	do
			npart=$(echo $dbdisk1 | awk '{print $1}')	# partition number
			fs=$(echo $dbdisk1 | awk '{print $4}')	# file system type (ext3, ext4, ...)
			md=$(echo $dbdisk1 | awk '{print $7}')	# md device mdX
			command_format=""
			
			for((n=0; n <= ${#FSTYPE[@]}-1; n++))
			do
				if [ "$fs" == "${FSTYPE[$n]}" ]; then
					command_format="${FORMAT_COM[$n]}"	# get command to format device
					break
				fi
			done
			
			if [ $md -ge 0 ]; then
				devtoformat="/dev/md${md}"	# if device is mdarray get his name 
			else
				devtoformat=""
			fi
			if [ -z "$command_format" ]; then	# if command_format is empty, it means does not need format or there is no command for it
			    logging "$devtoformat need not be formatted"
			    
			    # check if DISK_DB $ = LVM2_member. If yes run copy_lvm_to_new_disk
			    if [ "$fs" == "LVM2_member" ]; then
			    	copy_lvm_to_new_disk $npart $md
			    fi
			    continue
			fi

			error_formatting=""
			sleep 1
			if [ $md -lt 0 ]; then
				## Format partitions
				for ((g=1; g < ${#DISK[@]}; g++))
				do
					devtoformat="${DISK[$g]}${npart}"
					printing "Building file system (format): $command_format $devtoformat"
					printing_n "Formating... "
					

					trap ctlc_close_barformat 2
					if [ $DEBUG_MODE -eq 1 ]; then
						set +x		# not need to log ProgressBar (it's very long and repetitiv)
					fi
					>$BAR_SEMAF
					bar_format &
					
					if ! (${command_format} ${devtoformat} >>$LOGFILE 2>&1); then
						sleep .8	# wait for printing bar in case format was too fast
						"rm" -f $BAR_SEMAF >/dev/null 2>&1
						if [ $DEBUG_MODE -eq 1 ]; then
							set -x
						fi						
						sleep 1.2	# wait for bar_format to exit
						# something went wrong
						error_formatting="$error_formatting, $devtoformat"
						fatal_error "Unable to format ${devtoformat}!"
						exit 1
					else
						sleep .8	# wait for printing bar in case format was too fast
						"rm" -f $BAR_SEMAF >/dev/null 2>&1
						if [ $DEBUG_MODE -eq 1 ]; then
							set -x
						fi						
						sleep 1.2	# wait for bar_format to exit				
					fi											
				done
			else
				## Format mdarrays
				printing "Building file system (format): $command_format $devtoformat"
				printing_n "Formating... "
				trap ctlc_close_barformat 2
				if [ $DEBUG_MODE -eq 1 ]; then
					set +x		# not need to log ProgressBar (it's very long and repetitiv)
				fi
				>$BAR_SEMAF
				bar_format &
								
				if ! (${command_format} ${devtoformat} >>$LOGFILE 2>&1); then		# Build file system in device (Format device)
					sleep .8
					"rm" -f $BAR_SEMAF >/dev/null 2>&1
					if [ $DEBUG_MODE -eq 1 ]; then
						set -x
					fi					
					sleep 1.2	# wait for bar_format to exit				
					# something went wrong
					error_formatting="$error_formatting, $devtoformat"
					fatal_error "Unable to format ${devtoformat}!"
					exit 1
				else
					sleep .8
					"rm" -f $BAR_SEMAF >/dev/null 2>&1
					if [ $DEBUG_MODE -eq 1 ]; then
						set -x
					fi					
					sleep 1.2	# wait for bar_format to exit
				fi							

			fi
			sleep 1
			if [ $md -ge 0 ]; then
				copy_partition_to_new_disk $npart $md $fs
			fi
	
	done < $temp_DISK_DB
			
	# unmount all temp partitions
	printing "Unmounting partitions"

	while read mpt
	do
		umounter $mpt	# unmount $mpt trying 3 times and then forcing unmount if needed
	done < $TEMP/temp_mountpoints
	
	# ordering chroot_mtab as mount_clean
	if [ $BOOTP_MODE -eq 1 ]; then
		mount_clean_virtual
		MC=$MOUNT_CLEAN_VIRTUAL
	else
		mount_clean
		MC=$MOUNT_CLEAN 
	fi
	while read mtabr
	do
		mptab=$(echo $mtabr | awk '{print $2}')
		# chroot_mtab was created in partitioncopy to help the unmount process
		awk -v mptab="$mptab" '$2 == mptab {print}' $TEMP/chroot_mtab >> $TEMP/chroot_mtab1
	done < $MC
	#"cp" $MC $TEMP/mount_clean_3	# mount clean needed for step 3
	
	"mv" -f $TEMP/chroot_mtab1 $TEMP/chroot_mtab
	
	"rm" -fR ${MOUNTPOINT}	# remove old mountpoint directory with all subdirs
	mkdir -p ${MOUNTPOINT}	# create a new mountpoint directory
	
	# mount them to be used as chroot
	printing "Mounting chroot partition"
	devboot=""
	while read chr
	do
		devr=$(echo $chr | awk '{print $1}')
		dirmount=$(echo $chr | awk '{print $2}')
		mpr=${MOUNTPOINT}${dirmount}
		
		if [ "$GRUBNAME" == "2" -a "${dirmount}" == "/boot" ]; then
			devboot=$devr
		else
			if ! (mount $devr $mpr); then
				printerror "Unable to mount $devr"
			fi
		fi		
	done < $TEMP/chroot_mtab
	
	#"cp" $TEMP/mount_clean_3 ${MOUNTPOINT}${TEMP}/mount_clean_3
	
	create_mdadm_conf	

	# change config.raider to devicename types according to the original config files
	reconfig_config_files
	
	# copy config.raider files to chroot
	copy_conf_to_chroot

	# set selinux in rootpartition
	set_selinux

	mount --bind /sys ${MOUNTPOINT}/sys 2>>$LOGFILE
	mount --bind /proc ${MOUNTPOINT}/proc 2>>$LOGFILE
	mount --bind /dev ${MOUNTPOINT}/dev 2>>$LOGFILE
	
	# create file script to run inside chroot
	RUNCHROOT="${MOUNTPOINT}/RUN_CHROOT_RAIDER"
	>$RUNCHROOT
	chmod +x $RUNCHROOT
	error_check_chroot='if [ ${PIPESTATUS[0]} -ne 0 ]; then echo "Error_chroot_b" >> '${GRUBLILOLOG}' ; fi'
	error_mkinitrd_chroot='if [ ${PIPESTATUS[0]} -ne 0 ]; then echo "Error_chroot_mkinitrd" >> '${GRUBLILOLOG}' ; fi'
	
	# add commands to to RUNCHROOT script
	if [ "$GRUBNAME" == "1" ]; then
		if [ -f /usr/share/mkinitrd/mkinitrd_command_generator.sh ]; then
			systemmapv="/boot/System.map"
			vmlinuzv="/boot/vmlinuz"
			configv="/boot/config"
			if [ -e ${systemmapv}-generic${knm}-$(uname -r)${knm} ]; then								
				echo -e "\"rm\" $systemmapv $vmlinuzv $configv" >> $RUNCHROOT
				if uname -r | grep -q smp ; then
					knm="-smp"
				else
					knm=""
				fi
				echo "ln -s /boot/System.map-generic${knm}-$(uname -r)${knm} $systemmapv" >> $RUNCHROOT
				echo "ln -s /boot/vmlinuz-generic${knm}-$(uname -r)${knm} $vmlinuzv" >> $RUNCHROOT
				echo "ln -s /boot/config-generic${knm}-$(uname -r)${knm} $configv" >> $RUNCHROOT			
			fi
			echo 'eval $('$COM_MKINITRD') 2>&1 | tee -a '${GRUBLILOLOG} >> $RUNCHROOT
		else
			echo "$COM_MKINITRD 2>&1 | tee -a ${GRUBLILOLOG}" >> $RUNCHROOT
		fi
		#echo "$COM_MKINITRD 2>&1 | tee -a ${GRUBLILOLOG}" >> $RUNCHROOT
		echo "${error_mkinitrd_chroot}" >>$RUNCHROOT

		devmap1=$(create_grub1_device_map)
		create_grub1_run $devmap1
		cat $GRUB1_RUN_SCRIPT >> $RUNCHROOT

	elif [ "$GRUBNAME" == "2" ]; then
		if ! [ -z "$devboot" ]; then	# using GRUB2, if there is a device which owns /boot, it must be mounted inside chroot, 
										# not before chroot is mounted
			echo "mount $devboot /boot" >> $RUNCHROOT
		fi
		if [ -f /usr/share/mkinitrd/mkinitrd_command_generator.sh ]; then
			systemmapv="/boot/System.map"
			vmlinuzv="/boot/vmlinuz"
			configv="/boot/config"
			if [ -e ${systemmapv}-generic${knm}-$(uname -r)${knm} ]; then								
				echo -e "\"rm\" $systemmapv $vmlinuzv $configv" >> $RUNCHROOT
				if uname -r | grep -q smp ; then
					knm="-smp"
				else
					knm=""
				fi
				echo "ln -s /boot/System.map-generic${knm}-$(uname -r)${knm} $systemmapv" >> $RUNCHROOT
				echo "ln -s /boot/vmlinuz-generic${knm}-$(uname -r)${knm} $vmlinuzv" >> $RUNCHROOT
				echo "ln -s /boot/config-generic${knm}-$(uname -r)${knm} $configv" >> $RUNCHROOT			
			fi
			echo 'eval $('$COM_MKINITRD') 2>&1 | tee -a '${GRUBLILOLOG} >> $RUNCHROOT
		else
			echo "$COM_MKINITRD 2>&1 | tee -a ${GRUBLILOLOG}" >> $RUNCHROOT
		fi
		#echo "$COM_MKINITRD 2>&1 | tee -a ${GRUBLILOLOG}" >> $RUNCHROOT
		echo "${error_mkinitrd_chroot}" >>$RUNCHROOT

		# remove /boot from chroot_mtab
		awk '{ if($2 != "/boot") print}' $TEMP/chroot_mtab > $TEMP/chroot_mtab1
		"mv" -f $TEMP/chroot_mtab1 $TEMP/chroot_mtab
		
		### FIXME
		### dont install GRUB2 if UEFI
		if [ $UEFI_MODE -eq 0 ]; then
			for ((t=1; t < ${#DISK[@]}; t++))
			do
				echo "echo $GRUB_INSTALL --no-floppy --recheck ${DISK[$t]} >> ${GRUBLILOLOG}" >> $RUNCHROOT
				echo "$GRUB_INSTALL --no-floppy --recheck ${DISK[$t]} 2>&1 | tee -a ${GRUBLILOLOG}" >> $RUNCHROOT
				echo ${error_check_chroot} >>$RUNCHROOT
			done
		fi
		echo "echo $GRUB2_MKCONFIG -o $GRUB2_CFG >> ${GRUBLILOLOG}" >> $RUNCHROOT
		echo "$GRUB2_MKCONFIG -o $GRUB2_CFG 2>&1 | tee -a ${GRUBLILOLOG}" >> $RUNCHROOT
		echo ${error_check_chroot} >>$RUNCHROOT
		if ! [ -z "$devboot" ]; then
			echo "umount -l /boot" >> $RUNCHROOT
		fi
	elif [ "$BOOTLOADER" == "LILO" ]; then
		#if echo $DISTRO | grep -qi ^slackware ; then
		if [ -f /usr/share/mkinitrd/mkinitrd_command_generator.sh ]; then
			systemmapv="/boot/System.map"
			vmlinuzv="/boot/vmlinuz"
			configv="/boot/config"
			if [ -e ${systemmapv}-generic${knm}-$(uname -r)${knm} ]; then								
				echo -e "\"rm\" $systemmapv $vmlinuzv $configv" >> $RUNCHROOT
				if uname -r | grep -q smp ; then
					knm="-smp"
				else
					knm=""
				fi
				echo "ln -s /boot/System.map-generic${knm}-$(uname -r)${knm} $systemmapv" >> $RUNCHROOT
				echo "ln -s /boot/vmlinuz-generic${knm}-$(uname -r)${knm} $vmlinuzv" >> $RUNCHROOT
				echo "ln -s /boot/config-generic${knm}-$(uname -r)${knm} $configv" >> $RUNCHROOT			
			fi
			echo 'eval $('$COM_MKINITRD') 2>&1 | tee -a '${GRUBLILOLOG} >> $RUNCHROOT
		else
			echo "$COM_MKINITRD 2>&1 | tee -a ${GRUBLILOLOG}" >> $RUNCHROOT
		fi
		#echo "$COM_MKINITRD 2>&1 | tee -a ${GRUBLILOLOG}" >> $RUNCHROOT
		echo "${error_mkinitrd_chroot}" >>$RUNCHROOT
		echo "lilo -H -v 2>&1 | tee -a ${GRUBLILOLOG}" >> $RUNCHROOT	
		echo "${error_check_chroot}" >>$RUNCHROOT
	else
		fatal_error "Bootloader not supported!"	
		exit 1
	fi
	if [ -f /etc/rc.d/boot.md ]; then	# OpesSuSE needs this to run raid arrays after boot
		echo "chkconfig boot.md on 2>/dev/null" >> $RUNCHROOT	# /etc/rc.d/boot.md
	fi
	echo "exit" >> $RUNCHROOT
	
	printfile "$RUNCHROOT created:" $RUNCHROOT
	local ldisks=""
	for (( k=1; k < ${#DISK[@]} ; k++))
	do
		ldisks="${ldisks}${DISK[$k]} "
	done
	if [ -n "$COM_MKINITRD" ]; then
		printing "Create initram filesystem and install ${BOOTLOADER} in ${ldisks}"
		printing "$COM_MKINITRD"
	else
		fatal_error "Mkinitramfs generator command not found!"
		exit 1
	fi

	printing "Enter in chroot system..."
	chroot ${MOUNTPOINT} /bin/bash /RUN_CHROOT_RAIDER
	ERROR_INSIDE_CHROOT=""
	if (grep -q ^Error ${MOUNTPOINT}${GRUBLILOLOG} ); then
		noe=0
		if grep -q ^Error_chroot_b ${MOUNTPOINT}${GRUBLILOLOG} ; then
			ERROR_INSIDE_CHROOT="${BOOTLOADER} installation error!\n"
			noe=$(( noe+1 ))
		fi
		if grep -q ^Error_chroot_mkinitrd ${MOUNTPOINT}${GRUBLILOLOG} ; then
			ERROR_INSIDE_CHROOT="${ERROR_INSIDE_CHROOT}${MKINITRD} error!"
			noe=$(( noe+1 ))
		fi
		if [ $noe -eq 0 ]; then
			# if there is an error different from the first two, this is a grub 1 error
			# because it does not have a return value after quit
			ERROR_INSIDE_CHROOT="${BOOTLOADER} installation error!"
		fi
	fi
	if [ -e ${MOUNTPOINT}${GRUBLILOLOG} ]; then
		cat ${MOUNTPOINT}${GRUBLILOLOG} >> $LOGFILE
		cat ${MOUNTPOINT}${GRUBLILOLOG} > ${GRUBLILOLOG}
	fi
	"mv" ${RUNCHROOT} ${MOUNTPOINT}${R_LIB}/RUN_CHROOT_RAIDER

	logging "Copying logfiles to chroot"
	"cp" -vpf ${LOGFILE} ${MOUNTPOINT}${LOGFILE} >> $LOGFILE 2>&1		# copy logfiles to new disk before unmounting the system
	"cp" -vpf ${DEBUG_LOG} ${MOUNTPOINT}${DEBUG_LOG} >>$LOGFILE 2>&1	# 

	echo 3 > ${MOUNTPOINT}${STEP_FILE}					# sign step 3 in the new disk

	printing "Unmounting chroot system"
	umount_chroot
	if [ -n "$ERROR_INSIDE_CHROOT" ]; then	
		fatal_error "${ERROR_INSIDE_CHROOT}"
		cat ${GRUBLILOLOG}
		kernel_messages_on
		exit 1
	fi
	
	set_step 0		# return to the beginning (step 0 means step 2 has finished in original disk)
	kernel_messages_on
	printdivision
	echoing "Converting to Raid ${RAID_TYPE}"
	echoing "End of BuildRaid phase! Now follow the instructions:"
#	if (avoid_runlevel_1); then
#		exitmessage=""
#	else
#		exitmessage='in "single user" mode'
#	fi
	tempo=$(echo "scale=2;$SECONDS/60"|bc)
	logging "Raider BuildRaid phase took $tempo minutes to perform"
cat << EOF
--------------------------------------------------------------------
   1 - Swap the first (original) disk with the last one in the slot positions,
       after shutting down the computer. 
   2 - Switch on your computer again and boot the system
   3 - Run this command: "raider --run". 
       RaidSync will start at once.
--------------------------------------------------------------------
Raider BuildRaid phase took $tempo minutes to perform
EOF
}





