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

single_to_raid1() {		# Add a new disk and create a RAID1 array
	single_to_raid "R1" 2 
}

single_to_raid4() {		# Add 2 new disks and create a RAID4 array
	single_to_raid "R4" 3
}

single_to_raid6() {		# Add 3 new disks and create a RAID6 array
	single_to_raid "R6" 4
}

single_to_raid5() {		# Add 2 new disks and create a RAID5 array
	single_to_raid "R5" 3
}

single_to_raid10() {	# Add 3 new disks and create a RAID10 array
	single_to_raid "R10" 4
}

single_to_raid() {		# create RAID-X common function

	MAIN_COMMAND=$1
	MIN_DISKS=$2
	check_root
	kernel_messages_off
	: >$LOGFILE	# create a logfile
	date +%F" "%T >> $LOGFILE
	create_dirs
	printdivision
	logdivision
	printing "$PROGRAM_NAME version $VERSION started"
	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') 
	printing "$optmessage"
	logdivision
	# check if disks were not selected	
	numdisks=$(list_disks | wc -l)
	if [ ${#DISK[@]} -eq 0 ]; then
		if [ $numdisks -gt ${MIN_DISKS} ]; then	# not selecting disks, it must exist MIN_DISKS to select by default
			fatal_error "Found $numdisks disks in the system. Disks must be selected first!"
			echoing "RAID ${RAID_TYPE} needs ${MIN_DISKS} or more disks to work."
			kernel_messages_on
			exit 1
		elif [ $numdisks -lt ${MIN_DISKS} ]; then
			fatal_error "The system has only ${numdisks} disks, "
			echoing "and RAID ${RAID_TYPE} needs at least ${MIN_DISKS} disks to work."
			kernel_messages_on
			exit 1
		fi
		local n=0
		# if no disks were selected, and there are 3 in the system, get their device names
		for d in $(list_disks)
		do
			DISK[$n]=/dev/$d
			n=$((n+1))
		done
	else
		if [ ${#DISK[@]} -gt ${numdisks} ]; then
			fatal_error "The system has only ${numdisks} disks, and you selected ${#DISK[@]} disks!"
			kernel_messages_on
			exit 1
		elif [ ${numdisks} -lt ${MIN_DISKS} ]; then
			fatal_error "The system has only ${numdisks} disks, "
			echoing "and RAID ${RAID_TYPE} needs at least ${MIN_DISKS} disks to work."
			kernel_messages_on
			exit 1
		elif [ ${#DISK[@]} -lt ${MIN_DISKS} ]; then
			fatal_error "You must select at least ${MIN_DISKS} disks to create a RAID ${RAID_TYPE}"
			kernel_messages_on
			exit 1
		fi
	fi
	LASTDISK=$(( ${#DISK[@]}-1 ))
	# check if the first disk is the system disk
	local sysd=$(get_system_disk)
	if [ "$sysd" != "${DISK[0]}" ]; then
		fatal_error "${DISK[0]} is not the system disk!"
		echoing "The first device selected must be the system disk!"
		exit 1
	else
		logging "${sysd} is the system disk"
	fi
	####	check if system selected disks exist
	if ! [ -b "${DISK[0]}" ]; then
		fatal_error "${DISK[0]} does not exist or is not a device"
		kernel_messages_on
		exit 1
	fi

	nosecond=0
	for (( a=1 ; a < ${#DISK[@]} ; a++))
	do
		####    check if device exist
		if ! [ -b "${DISK[$a]}" ]; then
			ERRORS_N=( "${ERRORS_N[@]}" "$DISK_DOES_NOT_EXIST")
			ERRORS_V=( "${ERRORS_V[@]}" "${DISK[$a]}" )				
			nosecond=1
		fi	
	done
	# check if there are repeated disk names 
	for (( a=0 ; a <= $(( ${#DISK[@]}-1 )) ; a++))
	do
		for (( b=$(( a+1 )); b <= $(( ${#DISK[@]}-1 )); b++ ))
		do
			if [ "${DISK[$a]}" == "${DISK[$b]}" ]; then
				ERRORS_N=( "${ERRORS_N[@]}" "$DISKS_ARE_THE_SAME")
				ERRORS_V=( "${ERRORS_V[@]}" "${DISK[$a]}" )	
			fi
		done
	done

	
	####   check if selected disks are not empy or have some raid devices
	if [ $nosecond -eq 0 ]; then
		for (( d=1; d < ${#DISK[@]}; d++))
		do
			partitions_newdisk=$(env LC_ALL=C fdisk -l ${DISK[$d]} 2>/dev/null | grep ^"/dev")
			if ! [ -z "$partitions_newdisk" ]; then
				logging "ATENTION: ${DISK[$d]} is not empty."
				ERRORS_N=( "${ERRORS_N[@]}" "$DISK_NOT_EMPTY")
				ERRORS_V=( "${ERRORS_V[@]}" "${DISK[$d]}" )				
				raidpart=$(env LC_ALL=C fdisk -l ${DISK[$d]} 2>/dev/null | grep ^"/dev" | awk '{print $1}' | xargs -I {} mdadm -bE {} 2>/dev/null)
				if ! [ -z "$raidpart" ]; then
					logging "There are some Raid devices in ${DISK[$d]}:"
					logging "$raidpart"
					echo >> $LOGFILE
					ERRORS_N=( "${ERRORS_N[@]}" "$DISK_WITH_RAID")
					ERRORS_V=( "${ERRORS_V[@]}" "${DISK[$d]}" )
				fi
			fi
		done
	fi

	if [ "$KERNEL_VERSION" == "3.1.0" -a "$RAID_TYPE" == "10" ]; then
		fatal_error "Kernel version ($KERNEL_VERSION) has a serious bug related to Raid 10!"
		echoing "(https://bugzilla.kernel.org/show_bug.cgi?id=41862)"
		printing "Please update your kernel before running raider!"
		kernel_messages_on
		exit 1
	fi


	linux_distro > $R_LIB/distro_info
	DISTRO=$(awk 'NR==1' $R_LIB/distro_info)		## get informations about linux distro
	DISTRO_NAME=$(awk 'NR==2' $R_LIB/distro_info)
	DISTRO_VERSION=$(awk 'NR==3' $R_LIB/distro_info)
	
	
	printdivision
	check_distro_db	# check if distro was already tested against raider
	#printing "Linux distro found:  $DISTRO"
	printdivision
	if (check_distros_not_runlevel1); then
		fatal_error "Raider in $DISTRO, "
		echoing "must not run in single user mode!"
		kernel_messages_on
		exit 1
	fi	
	echo -n "Press any key... "
	read -n1
	echo -ne "\r\033[1A"
	
	PARTITION_TABLE_TYPE=$(ptable_type ${DISK[0]})
	if [ $BOOTP_MODE -eq 1 ]; then	# if forced bootp_mode (with -b option)
		check_support_bootp	# check if this is possible
		rt=$?
		if [ $rt -eq 1 ]; then
			fatal_error "-b option not supported!"
			echoing "There is already a /boot partition."
			kernel_messages_on
			exit 1
		elif [ $rt -eq 2 ]; then
			fatal_error "-b option only supported in msdos partition"
			echoing "Partition table is $PARTITION_TABLE_TYPE." 
			kernel_messages_on
			exit 1
		else
			BOOTRAID1_MODE=1	# force bootraid1_mode
			printing "A new \"/boot\" partition with $BOOTP_SIZE size and a $BOOTP_FS filesystem"
			printing "will be added in the new disk. Use \"-b\" option to change parameters"
			printdivision
		fi
	fi
# 	if [ $SWAPRAIDER_MODE -eq 1 ]; then
# 		printing "Swapraider is on"
# 		printdivision
# 	fi
	if (check_selinux); then
		printing "Selinux is enabled."
		echoing "It's recommended to disable selinux to speed up raider process."
		printdivision
	fi

	echo "MAIN_COMMAND=${MAIN_COMMAND}" > $VARSFILE
	echo "RAID_TYPE=${RAID_TYPE}" >> $VARSFILE
	echo "PARTITION_TABLE_TYPE=${PARTITION_TABLE_TYPE}" >> $VARSFILE	
	create_database		## create a database describing each partition in the original disk.
	
	list_disks_selected		# output a list of disks selected and partitions
							# this function also runs "mount_clean"
	echo -e "DISTRO=\"$DISTRO\"" >> $VARSFILE
	# save disk1 and disk2 names to files
	echo "DISK[0]=${DISK[0]}" >> $VARSFILE
	
	for (( a=1 ; a < ${#DISK[@]} ; a++))
	do
		echo "DISK[$a]=${DISK[$a]}" >> $VARSFILE 
	done
	echo "LASTDISK=${LASTDISK}" >> $VARSFILE
	echo -e "RAID_EXT=\"$RAID_EXT\"" >> $VARSFILE
	if [ $nosecond -eq 0 ]; then
		for (( a=1 ; a < ${#DISK[@]} ; a++))
		do
			if [ $(d_info_space_bytes ${DISK[$a]}) -lt $(d_info_space_bytes ${DISK[0]}) ]; then
				ERRORS_N=( "${ERRORS_N[@]}" "$DISK_NOT_ENOUGH_SPACE")
				ERRORS_V=( "${ERRORS_V[@]}" "${DISK[$a]}" )			
			fi
		done
	fi
	
	if [ -n "$PARTITION_TABLE_TYPE" ]; then
		printing "${DISK[0]} partition table type: ${PARTITION_TABLE_TYPE}"
	else
		fatal_error "Partition table not found in ${DISK[0]}"
		kernel_messages_on
		exit 1
	fi	
	check_bootloader	## check if bootloader exists, what version is installed 
	local cbret=$?
	if [ $cbret -eq 1 ]; then	## and obtain config file path and other several parameters 
		fatal_error "Bootloader does not exist in ${DISK[0]}!"
		kernel_messages_on
		exit 1
	elif [ $cbret -eq 2 ]; then
		fatal_error "Raider does not support UEFI systems yet!"
		echoing "** This will be supported in raider version 0.20 **"
		echoing "Consider to boot in BIOS mode. This way raider is able to run"
		exit 1	
	fi

	get_mkinitrd_com
	if [ $? -ne 0 ]; then
		printdivision
		fatal_error "To be able to boot to a raid system"
		printing "raider needs an initramfs generator"
		# there is some relationship between the package manager and the initramfs generator
		# used in each distro, so we can use it to deduce which is the initramfs generator.
		if type emerge >/dev/null 2>&1 ; then	# gentoo like
			printing "Please install ${cB}genkernel${cEnd} or ${cB}dracut${cEnd}"
		elif type pacman >/dev/null 2>&1 ; then	# archlinux like
			printing "Please install ${cB}mkinitcpio${cEnd}"	
		elif type yum >/dev/null 2>&1 ; then	# redhat like
			printing "Please install ${cB}dracut${cEnd}, or ${cB}mkinitrd${cEnd}"
		elif type apt-get >/dev/null 2>&1; then	# debian like 
			printing "Please install ${cB}mkinitramfs${cEnd}"
		elif type zypper >/dev/null 2>&1; then	# opensuse like
			printing "Please install ${cB}mkinitrd${cEnd}"
		elif type urpmi >/dev/null 2>&1; then	# mandriva like
			printing "Please install ${cB}dracut${cEnd} or ${cB}mkinitrd${cEnd}"	# dracut only 2011 or later
		elif type installpkg >/dev/null 2>&1; then
			printing "Please install ${cB}mkinitrd${cEnd}"
		fi
		printing "and create an initramfs file to boot the system."
		exit 1
	fi
	if [ "$MKINITRD" == "mkinitcpio" ]; then
		local HK=$(grep ^HOOKS= ${NEW_MKINITCPIO} | sed -e s'/HOOKS=//'g -e s'/\"//'g)
		logging "${MKINITCPIO_CONF} new HOOKS values:"
		echo "HOOKS=${HK}" >> ${LOGFILE}
	fi

	
	if [ $BOOTP_MODE -eq 0 ]; then	# if bootp_mode was not forced by -b option
		check_support_bootp	# check if there is already a /boot partition
		if [ $? -eq 0 ]; then	# bootp_mode is supported so check if it is really needed
			#is_bootp_needed
			is_bootraid1_needed
			if [ $? -eq 0 ]; then
				BOOTRAID1_MODE=1
				logging "A separated raid 1 boot partition will be created. BOOTP_MODE=1, BOOTRAID1_MODE=1"
				printdivision
				echoing "WARNING: This system will need a separated raid 1 /boot partition"
				echoing "to be able to boot!"
				echoing "This will be done automatically."
				echoing "A new \"/boot\" partition with $BOOTP_SIZE size and a $BOOTP_FS filesystem"
				echoing "will be added to the new system."
				echoing "If you want to change to a diferent size or filesystem, use \"-b\" option."		
				printdivision
				BOOTP_MODE=1	# force bootp in this specific case
			fi
		else
			if is_bootraid1_needed ; then	# if bootp_mode = 0 but raid1 is needed in boot partition
				BOOTRAID1_MODE=1
			fi
		fi
	fi
	if [ $BOOTP_MODE -eq 1 ]; then	# let's create the boot partition in the disk_db if possible
		create_disk_virt
	fi	

	create_bootloader_conf	## the new grub conf to be used after raid is working in both disks
							## disk_virt must be created before

	if [ $SWAPRAIDER_MODE -eq 1 ]; then
		printdivision
		if [ -n "$vResume" ]; then
			printing "Swapraider is on (because there is a resume kernel option)"
		else
			printing "Swapraider is on"
		fi
		printdivision
	fi

	echo "BOOTP_MODE=${BOOTP_MODE}" >> $VARSFILE
	echo "BOOTRAID1_MODE=${BOOTRAID1_MODE}" >> $VARSFILE
	printfile "$VARSFILE file:" $VARSFILE
	if [ "$BOOTLOADER" == "GRUB" ]; then
		printfile "Grub ${GRUBNAME} configuration file found in the system ($MENULST):" ${MENULST}
		printfile "Grub ${GRUBNAME} configuration file created ($NEWMENULST_MD):" ${NEWMENULST_MD}
		if [ -f ${MENULST_EXTRA1} ]; then
			printfile "Grub 2 extra configuration file found in system ($MENULST_EXTRA1):" ${MENULST_EXTRA1}
			printfile "Grub 2 extra configuration file created ($MENULST_EXTRA1):" ${NEWMENULST_MD_EXTRA1}
		fi
	elif [ "$BOOTLOADER" == "LILO" ]; then
		printfile "LILO-${LILO_VERSION} configuration file found in system ($MENULST):" ${MENULST}
		printfile "LILO-${LILO_VERSION} configuration file created ($NEWMENULST_MD):" ${NEWMENULST_MD}
	fi	
	printfile "Device ${DISK[0]} partition structure database:\n
Partition  PartitionType  TotalSizeSectors  FileSystemType Supported MountPoint RaidArrayNumber FstabDevNameType GrubDevNameType Flag PartNameinGPT StartSize EndSize" $DISK_DB
	
	if [ $BOOTP_MODE -eq 1 ]; then
		printfile "New disk partition structure database, with a NEW BOOT PARTITION:\n
Partition  PartitionType  TotalSizeSectors  FileSystemType Supported MountPoint RaidArrayNumber FstabDevNameType GrubDevNameType Flag PartNameinGPT StartSize EndSize" $DISK_DB_VIRTUAL
	fi
	
	printfile "${FSTAB} found in system" ${FSTAB}
	create_fstab		## new fstab and mtab that is pointing to new /dev/mdX devices
	printfile "Created new ${FSTAB}" ${NEWFSTAB}
	if (check_need_mtab); then
		logging "${MTAB} found in system" ${MTAB}
		logging "Created new ${MTAB}" ${NEWMTAB}
	else
		logging "$MTAB is a softlink to $(readlink -e $MTAB)."
		logging "We don't need to create a new $MTAB file"
	fi
	
	## Display error messages when they exist
	if [ "$BOOTLOADER" == "GRUB" ]; then
		if [ "$GRUB_VERSION" == "2" ]; then
			if ! (check_final_errors); then
				ERRORS_N=( "${ERRORS_N[@]}" "$VARIABLE_EMPTY")
				ERRORS_V=( "${ERRORS_V[@]}" " " )			    
			fi
		fi
	fi	

	# check if disks > 2T and metadata=0.90
	# Disks > 2Tb are not able to boot in raid arrays with 0.90 metadata.
	# To boot in raid arrays, Lilo and Grub1 needs metadata 0.90 to boot.
	# So, Grub 1 and LILO need disks smaller then 2Tb to boot in raid arrays.
	# 
	local d2t=$(check_2T_metadata)
	if [ -n "$d2t" ]; then
		if [ "$GRUBNAME" != "2" ]; then
			ERRORS_N=( "${ERRORS_N[@]}" "$DISK_INCOMPATIBLE")
			ERRORS_V=( "${ERRORS_V[@]}" "$d2t" )			
		fi
	fi
	
	# check if Vector linux has no LILO installed
	if echo "$DISTRO" | grep -qi ^"vector linux" ; then
		if [ "$BOOTLOADER" != "LILO" ]; then
			ERRORS_N=( "${ERRORS_N[@]}" "$FATAL_ERROR")
			ERRORS_V=( "${ERRORS_V[@]}" "Raider is not able to run in Vector Linux with $BOOTLOADER" )
		fi
	fi
	if [ ${#ERRORS_N[@]} -gt 0 ]; then
		local fatal=0
		printdivision
		echoing "${#ERRORS_N[@]} ERROR(S) DETECTED:"
		for (( ds=0; ds <= ${#ERRORS_N} ; ds++ ))
		do
			case ${ERRORS_N[$ds]} in
				$DISK_DOES_NOT_EXIST)
					fatal_error "New disk ${ERRORS_V[$ds]} does not exist or is not a device!"
					fatal=1
					;;
				$DISK_NOT_EMPTY)
					fatal_error "New disk ${ERRORS_V[$ds]} is not empty!"
					if [ "${ERRORS_V[$ds]}" != "${DISK[0]}" ]; then
						echoing "${cB}ADVICE:${cEnd}"
						echoing ":: To erase ${ERRORS_V[$ds]} run the command: \"raider --erase ${ERRORS_V[$ds]}\""
					fi
					fatal=1
					;;
				$DISK_WITH_RAID)
					echoing "ERROR: ${ERRORS_V[$ds]} has partitions with Raid arrays!"
					;;
				$DISK_NOT_MOUNTED)
					echoing "ERROR:${ERRORS_V[$ds]} is not mounted!"
					;;
				$DISK_NON_LINUX)
					echoing "ERROR: ${ERRORS_V[$ds]} has non-linux partitions!"
					;;

				$DISKS_ARE_THE_SAME)
					fatal_error "You named two disks with the same name (${ERRORS_V[$ds]})!"
					fatal=1
					;;
				$DISK_INCOMPATIBLE)
					fatal_error "Disk(s) ${ERRORS_V[$ds]}is greater then 2 Terabytes."
					echoing "Only Grub 2 is able to boot raid arrays with hard disks larger then 2Tb"
					fatal=1
					;;
				$VARIABLE_EMPTY)
					echoing "Raider was not able to get all grub items. See raider --log"
					;;
				$DISK_NOT_ENOUGH_SPACE)
					fatal_error "Disk ${ERRORS_V[$ds]} is smaller then ${DISK[0]}"
					fatal=1
					;;
				$KERNEL_RAID_UNABLE) fatal_error "Initramfs file not found, and there are no raid drivers compiled in kernel."
					echoing "${cB}ADVICE:${cEnd}"
					echoing ":: Before running raider you nedd to compile a new kernel with raid drivers, or create a initramfs"
					;;
				$FATAL_ERROR) fatal_error "${ERRORS_V[$ds]}"
					fatal=1
					;;
				$ERROR_MESSAGE) echoing "${ERRORS_V[$ds]}"
					;;	

			esac
		done
		if [ $fatal -eq 1 ]; then
			echoing "Step 1 aborted..."
			set_step 0
			# don't delete all dirs while developping. We need them to debug
			#delete_all_dirs
			if [ -n "$vResume" ]; then
				swapraider_message 
			fi
			warn_to_logfile
			kernel_messages_on
			exit 1
		fi
	fi
	set_step 2	## Next time --run goes to step 2
	## All info was obtained until here
	## Prepare the second disk now
	if [ -n "$vResume" ]; then
		swapraider_message " :: "
	fi
	kernel_messages_on
	if [ $TEST_MODE -eq 1 ]; then
		echo
		echo "Everything seems to be ok! Check output messages and logfile."
		echo "You can continue to step 2 running: # raider --run"
		echo
	else
		export TEST_MODE
		go_step_2
	fi
}

warn_to_logfile() {		# tail message
cat << EOF
------------------------------------------------------------
WARNING:
Use "raiderl" command to display the logfile.
------------------------------------------------------------
EOF
}

swapraider_message() {	# warning message when there is a resume kernel option
local pref=$1
if [ $SWAPRAIDER_MODE -eq 1 ]; then
	return
fi
printdivision
printing "ATENTION:"
printing "There is a "resume=" kernel option pointing to a swap"
printing "partition device used to software suspend."
if [ $NO_SWAPRAIDER -eq 0 ]; then
	printing "It is advisable to use "-s" option!"
else
	printing "The resume option will point to the original device (not raid)"
fi
printdivision
	
#cat << EOF
#-------------------------------------------------------
#ATENTION:
#There is a "resume=" kernel option pointing to a swap
#partition device used to software suspend.
#It is advisable to use "-s" option!
#-------------------------------------------------------
#EOF
}


