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

go_step_3() {	# run step 3 (RaidSync phase)
	source $VARSFILE

	printdivision
	logdivision
	date +%F" "%T >> $LOGFILE
	printing "$PROGRAM_NAME version $VERSION started"
	printing "Conversion to Raid ${RAID_TYPE}"
	printing "RaidSync phase started..."
	printdivision
	logdivision
	if (check_runlevel_S); then
		if (avoid_runlevel_1); then
			fatal_error "Raider in $DISTRO, must not run in single user mode"
			echoing "Please change to multiuser mode!"
			exit 1
		fi
	else
		if ! (avoid_runlevel_1); then
#			if (need_runlevel_1); then
#				echoing "ATTENTION!!!"
#				printing "Raider in $DISTRO might have problems not running in single mode!"
#			else
				printing "You are not running in \"single user\" mode."
#				printing "If you will find some issues, try running in \"single user\" mode"
#			fi
			echoing_n "Do you want to continue without changing to single mode? (y/[n])"
			read cnt1
			if ! [ "$cnt1" == "y" -o "$cnt1" == "Y" ]; then
				echoing "Aborted!"
				echoing "Change to \"single mode\" and then enter \"raider --run\""
				exit 1
			fi
		else
			printing "Not running in \"single\" mode which is ok to ${DISTRO}"
		fi		
	fi	
	printdivision
	logdivision
	SECONDS=0
	kernel_messages_off
	sleep .5
	local n=0

	# how many disks exist
	countdisks=$(list_disks | wc -l)
	# how many disks were raided
	countraided=$(cat ${DISKS_STEP3} | wc -l)
	# the difference must be =1
	if [ $(( countdisks - countraided )) -ne 1 ]; then
		fatal_error "There are ${countdisks} disks in the system. Raider was expecting $((countraided+1))."
		echoing "Check disks connected..."
		exit 1
	fi
	
	local wrong_slot=0
	local new_disk=""
	local NEW
	local n=0

	for dev_d in $(list_disks)
	do
		# dev_d = /dev/disk 
		# id_dev = disk identification
		# dev_expected = /dev/disk before swapping disks
		id_dev="$(d_info_model /dev/${dev_d})--$(d_info_serial /dev/${dev_d})"
		dev_expected=$(awk -v id="${id_dev}" '$2==id {print $1}' ${DISKS_STEP3})
		if [ -z "${dev_expected}" ]; then
			if [ "${DISK[$LASTDISK]}" != "/dev/${dev_d}" ]; then
				# incorrect position for the unknown new disk
				fatal_error "/dev/${dev_d} is not connected in the correct slot."
				echoing "New disk must be connected to the last slot!"
				exit 1
			else
				new_disk=${dev_d}
			fi
		else
			printing "Detected /dev/${dev_d} as part of the new system"
		fi
	done

	NEW=$LASTDISK
	if [ ${DISK[$LASTDISK]} == "/dev/${new_disk}" ]; then
		printing "Detected /dev/${new_disk} as the new disk to be added to the raid system:"
		printing "$(d_info_name /dev/${new_disk}): $(d_info_model /dev/${new_disk}) - $(d_info_serial /dev/${new_disk})"
	else
		fatal_error "Something wrong with device connections! "
		echoing "New disk must be connected to the last slot"
		exit 1
	fi
	
	# check if raid arrays needed are running
	while read mdp
	do
		md=$(echo $mdp | sed 's/\/dev\///g')
		if ! (grep -q ^${md} /proc/mdstat ); then
			fatal_error "Raid array ${mdp} not running!"
			exit 1
		else
			if [ -z "$(awk -v md="$md" '$4 == md {print $4}' /proc/partitions)" ]; then
				fatal_error "Raid array ${mdp} does not exist"
				exit 1
			fi
		fi
	done < <(awk '{print $1}' $ADDERARRAY)
	printing "Raid arrays are running"
	
	# Check if raid arrays are all mounted
	
	printing "Check mounted devices:"
	while read mnt2
	do
		dev_3=$(echo "$mnt2" | awk '{print $1}')	# device name
		devA_3=$(realdev $dev_3)	# real device as it's written in /proc/partitions
		mpoint_3=$(echo "$mnt2" | awk '{print $2}')	# mountpoint related to device
		if [ -n "$devA_3" ]; then
			# only consider devices detected
			dv_3=$(mount | grep ^/dev | awk -v m="$mpoint_3" '$3 == m {print $1}' )
			dvA_3=$(realdev $dv_3)
			if [ "$dvA_3" != "$devA_3" ]; then
				fatal_error "${dev_3} is not mounted in ${mpoint_3} !"
				exit 1
			else
				printing " ${dev_3} --> ${mpoint_3}"
			fi
		fi
	done < $TEMP/chroot_mtab
	printing "Partitions are mounted as expected!"
	
	# check if there are other raid arrays running
	local foreign_array=""
	while read mdother
	do
			grep -q /dev/${mdother} $ADDERARRAY
			if [ $? -ne 0 ]; then
				foreign_array="${foreign_array}/dev/${mdother}\n"
			fi
				
	done < <(awk '/^md/ {print $1}' /proc/mdstat)
	if [ -n "$foreign_array" ]; then
		fatal_error "Detected raid arrays not supposed to exist here!"
		echoing "${foreign_array}" 
		exit 1
	fi

	# Compare sum of space partitions in disk0, with disk1 disk space
	if [ $(total_space_partitions ${DISK[0]}) -ge $(sfdisk -s ${DISK[$NEW]}) ]; then
		fatal_error "Not enough disk space in ${DISK[$NEW]}"
		echoing "Get a larger size disk!"
		exit 1
	fi
	
	# check total disk space. Better if they are equal
	if [ $(sfdisk -s ${DISK[0]}) -ne $(sfdisk -s ${DISK[$NEW]}) ]; then
		printing "WARNING: Disks have different sizes. This is not recommended,"
		printing "but it may work anyway..."
		echoing_n "Do you want to continue? (y/[n])"
		read rsp
		echo
		if ! [ "$rsp" == "y" -o "$rsp" == "Y" ]; then
			echoing "Step 3 aborted!"
			exit 1
		fi
	fi
	
	# check if disk not empty
	if (fdisk -l ${DISK[$NEW]} 2>/dev/null | grep -q ^/dev); then
		# delete disk
		printing "Disk ${DISK[$NEW]} is not empty. Deleting all data "
		delete_disk "${DISK[$NEW]}"
		if ( sfdisk -R ${DISK[$NEW]} 2>&1 | grep -q "currently in use"); then
			echoing "The system must reboot now! After rebooting run: \"raider --run\" again."
			echo "Please press any key..."
			read -n1 p
			init 6
		fi
		printing "Disk ${DISK[$NEW]} deleted"
	else
		printing "Disk ${DISK[$NEW]} already empty"
	fi
	printing "Cloning partitions from ${DISK[0]} to ${DISK[$NEW]}" 
	
	clone_gpt_partition ${DISK[$NEW]}
	res=$?
	if [ $res -eq 1 ]; then	# clone as a mbr partition
		pt_part="msdos"
		sfdisk -d ${DISK[0]} 2>/dev/null | sfdisk -f ${DISK[$NEW]} 2>$TEMP/sfd >/dev/null
		partprobe ${DISK[$NEW]}
	elif [ $res -eq 2 ]; then		# exit if disk in use
		echoing "The system must reboot now! After rebooting run: \"raider --run\" again."
		echo "Please press any key..."
		read -n1 p
		init 6
		return 1
	else
		pt_part="gpt"
	fi	
	sync
	sleep 1
	
	##  if a nonraid swap partition was created in the diskS, we must format it and swapon
	if [ -f ${SWAP_NEED_FORMAT} ]; then
		
		swappart=${DISK[$NEW]}$(head -n1 ${SWAP_NEED_FORMAT})
		if [ -n "$swappart" ]; then
			printing "Enable ${swappart} swap device in ${FSTAB}"
			sed -i.tmp "s/${SWAP_PRFIX}//g" ${FSTAB}
			"rm" -f ${FSTAB}.tmp
			printing "Building file system (format): mkswap -f ${swappart}"
			mkswap -f ${swappart}
			swapon ${swappart}
			printing "Enabled swap partition ${swappart}"
			local temp_DISK_DB
			if [ $BOOTP_MODE -eq 1 ]; then
				temp_DISK_DB=$DISK_DB_VIRTUAL
			else
				temp_DISK_DB=$DISK_DB
			fi
			typeofdev=$(awk '$4 == "swap" {print $8}' $temp_DISK_DB)
			new_swap=$(dev2devtype "${swappart}" "$typeofdev")
			# substitute swappart in fstab
			slash_new_swappart=$(echo ${new_swap} | sed 's/\//\\\//g')
			slash_oldswap=$(echo ${swappart} | sed 's/\//\\\//g')
			sed -i.tmp "s/$slash_oldswap/$slash_new_swappart/g" ${FSTAB}
			"rm" -f ${FSTAB}.tmp
			printing "Fixed swap name device in ${FSTAB}: ${new_swap}"
		fi
	fi
	
	

	# speed up raid sync
	speed_min=$(cat /proc/sys/dev/raid/speed_limit_min)
	speed_max=$(cat /proc/sys/dev/raid/speed_limit_max)
	new_min=$((speed_max/2))

	local error_add=0
	printing "Adding ${DISK[$NEW]} partitions to raid devices"
	while read raidl
	do
		mdadm $(echo $raidl | awk -v dv="${DISK[$NEW]}" '{print $1" -a "dv$2}') | tee -a ${LOGFILE}
		if [ $? -ne 0 ]; then
			error_add=1
		fi
		sleep 2
	done < ${ADDERARRAY}
	#echo $new_min >/proc/sys/dev/raid/speed_limit_min
	if [ ${error_add} -gt 0 ]; then
		fatal_error "Raider aborted!"
		exit 1
	fi
	
	echoing "${BOOTLOADER} will be installed in ${DISK[$NEW]} only after disks are synced, so..."
	echoing "WAIT UNTIL RAIDER FINISHES!"
	echoing "Don't stop this process."
	echoing ""
	if (check_runlevel_S); then
		# only speed up syncraid if in runlevel 1
		echo $new_min >/proc/sys/dev/raid/speed_limit_min	
	fi
	mdresync
	echo
	echo $speed_min >/proc/sys/dev/raid/speed_limit_min
	check_raid
	if [ $? -eq 0 ]; then
		printing "Devices are in sync!"
	else
		printing "ERROR: Devices not synced. Raider aborted!!!"
		exit 1
	fi	
	"rm" -f ${GRUBLILOLOG} >/dev/null 2>&1
	printing "Installing bootloader in ${DISK[${LASTDISK}]} to make it bootable"
	install_bootloader_step3	# better to install it after sync, to allow /boot replicate in last disk
	if [ $? -ne 0 ]; then
		printing "ERROR: ${BOOTLOADER} install error. Raider aborted!!!"
		exit 1
	fi
	set_step 1
	kernel_messages_on
	echo
	tempo=$(echo "scale=2;$SECONDS/60"|bc)
	logging "Raider RaidSync phase took $tempo minutes to perform"
cat << EOF
----------------------------------------------------
$DISTRO
Conversion to Raid ${RAID_TYPE} is ended!
----------------------------------------------------
Raider RaidSync phase took $tempo minutes to perform
EOF
}




