#!/bin/bash
#
# bootloader functions (not only grub)
# This file is part of Raider


add_grub_devtype_to_db() {	# add grub device type name in "kernel=" to the database disk_db
	
	dev=$1				# e.g. /dev/disk/by-id/xxx
	typedev=$(devtype "$dev")	# e.g.: by-id
	
	## take care of LVM2 if it exists, and get partition from /dev/sdX
	check_if_dev_is_lvm $dev
	if [ $? -eq 0 ]; then
	    volname=$(env LC_ALL=C lvdisplay -c "$dev" | awk 'BEGIN {FS=":"} {print $2}')
	    devdev=$(env LC_ALL=C pvs | awk -v volname="$volname" '$2 ~ volname {print $1}')
	else
	    devdev=$(realdev $dev)
	fi
	npart=$(echo "$devdev" | sed "s/\/dev\/[hs]d.//g")
	awk -v npart=$npart -v typedev="$typedev" '$1 == npart {$9 = typedev} {print}' $DISK_DB > $DISK_DB.tmp
	"mv" -f $DISK_DB.tmp $DISK_DB
}


bootloader_embedded() {		# get the name of bootloader
	# only supports grub or lilo
	if (dd if=${DISK[0]} bs=512 count=1 2>/dev/null | grep -qb "GRUB "); then
		echo "GRUB"
	elif (dd if=${DISK[0]} bs=512 count=1 2>/dev/null | grep -qb "LILO"); then
		echo "LILO"
	else
		# OpenSuSE have a lot of changes and patches to grub, and the name GRUB was removed
		if (echo $DISTRO | grep -qi suse); then	# check if distro is SuSE
			# bootloader is a patched GRUB 
			echo "GRUB patched"
		else
			echo "Unknown bootloader"
			return 1
		fi
	fi
}


# In this function, include code that change kernel options in grub if needed
change_kernel_options() {	 # change kernel options if needed
	local k_o=$1	
	# Remove rd_NO_MD from kernel options if it exists
	# This option may exist in systems with dracut, and prevents raid driver to be installed (we don't want it)
	k_o=$(echo "$k_o" | sed -e "s/ rd_NO_MD / /g" -e "s/ rd.md=0 / /g")
	 check if "domdadm" must be included 
	 it must be used with genkernel when raid modules must be loaded 
	echo "$COM_MKINITRD" | grep -q ^genkernel
	if [ $? -eq 0 ]; then
		echo "${k_o}" | grep -q domdadm 
		if [ $? -ne 0 ]; then
			k_o=$(echo "${k_o} domdadm")
			logging "domdadm added to kernel options"
		fi
	fi
	echo "$k_o"
}


check_bootloader() {		# Check if bootloader exist, and collect information about it
	#echoing "Scanning ${DISK[0]} for a boot manager embedded..."
	if ! (is_boot_manager_in_mbr); then
		printing "Bootloader not found in the boot sector."
		return 1
	else
		bootloadername=$(bootloader_embedded)
		resboot=$?
		BOOTLOADER=$(echo $bootloadername | cut -d' ' -f1)	# in Suse distro, the name is "GRUB patched"
		if [ $resboot -eq 0 ]; then
			printing "Bootloader found in the boot sector: $bootloadername"
		else
			if check_if_efi ${DISK[0]} ; then
#			if [ $resboot -eq 1]; then
				printing "Found a UEFI-GRUB system!"
				return 2	# comment this "return" when eufi mode is completely fubctional
				BOOTLOADER="GRUB"	# FIXME check other possibilities also, namely STUB KERNEL, elilo
				UEFI_MODE=1			# FIXME get also the partition number of uefi partition
				UEFI_PART=1			# FIXME here we consider uefi partition is 1. But there must be a function to
									# consider different partitions
			else
				printing "$bootloadername"
				return 1
			fi
		fi		
	fi
	## after finding which bootloader is used, get the version, get bootloader items 
	## if raid drivers are built in kernel or they exist in modules.
	if [ "$BOOTLOADER" == "LILO" ]; then	 	
		if (type lilo >/dev/null 2>&1 ); then
			LILO_VERSION=$(lilo -V | sed 's/LILO version //g')
			printing "LILO version: $LILO_VERSION"
			get_lilo_items
			if [ -z "$vInitrd" ]; then
				printing "$BOOTLOADER bootloader does not have references to a initrd file"
			fi
			return
			
		else
			fatal_error "LILO exists in MBR but is not installed in the system. Program aborted!"
			exit 1
		fi
	elif [ "$BOOTLOADER" == "GRUB" ]; then
		if (type grub >/dev/null 2>&1 ); then
			GRUBNAME="1"	# command grub does not exist in version 2
			GRUB_VERSION="$(grub --version | sed 's/.*\([0-9]\.[0-9]*\).*/\1/g')"			
		else
			for i in $GRUB2_INSTALL_NAME_LIST	# grub-install can have other names (e.g.: grub2-install)
			do
				if (type $i) >/dev/null 2>&1 ; then
					GRUBNAME="2"
					GRUB_VERSION="$($i --version | sed 's/.*\([0-9]\.[0-9]*\).*/\1/g')"
					GRUB_INSTALL=$(type -p $i)
					break
				fi
			done
		fi	
		printing "GRUB $GRUBNAME version: $GRUB_VERSION"
		if [ "$GRUBNAME" == "1" ]; then
			get_grub1_items
			if [ -z "$vInitrd" ]; then
				printing "$BOOTLOADER bootloader does not have references to a initrd file"
			fi			
		fi
		if [ "$GRUBNAME" == "2" ]; then
			get_grub2_items
			if [ -z "$vInitrd" ]; then
				printing "$BOOTLOADER bootloader does not have references to a initrd file"
			fi			
		fi	
	else
		return 1
	fi
}


check_if_efi() {	# Check if there is a EFI partition
	local disk=$1
	local fs flag
	#local tp=$(dd if=$disk bs=512 count=1 2>/dev/null | hexdump -v -s 450 -n 1 -e '1/1 "%02X"')
	# some hexdump versions have a issue with pipes giving error. So we avoid pipes in hexdump.
	dd if=$disk bs=512 count=1 2>/dev/null > $TEMP/efi.0
	local tp=$(hexdump -v -s 450 -n 1 -e '1/1 "%02X"' $TEMP/efi.0)
	if [ "$tp" == "EE" ]; then
		# this is a GPT partition
		flag=$(parted_machine ${DISK[0]} | sed 's/;$//' | awk -F: '$1=="1" {print $7}')
		fs=$(parted_machine ${DISK[0]} | sed 's/;$//' | awk -F: '$1=="1" {print $5}')
		if echo "$flag" | grep -q boot && [ "$fs" == "fat32" ]; then
				return 0	# this is a UEFI-GRUB
		fi
	fi
	return 1
}

check_kernel_option_bootdegraded() {	# if mkinitramfs, write bootdegraded in kernel options, to allow booting a degraded array
	if (type update-initramfs >/dev/null 2>&1 ); then
		opt='bootdegraded=true'
		if [ "$GRUBNAME" == "1" ]; then
			set_kernel_option_grub1 $opt 
		elif [ "$GRUBNAME" == "2" ]; then
			set_kernel_option_grub2 $opt GRUB_CMDLINE_LINUX ${NEWMENULST_MD} "add"
		fi
	fi
}


check_kernel_option_dmraid() {	# check if kernel option disabling dmraid exists
	local kdmr=$1
	if (echo "$kdmr" | grep -q -e ' rd_NO_DM ' -e ' rd.dm=0 '); then
		return 0
	else
		return 1
	fi
}


create_bootloader_conf() {		# create new bootloader conf file 
	if [ "$BOOTLOADER" == "LILO" ]; then
		create_lilo_conf
	elif [ "$GRUBNAME" == "1" ]; then
		create_grub1_conf
	else
		create_grub2_conf
		set_kernel_option_grub2 0 GRUB_DEFAULT $NEWMENULST_MD "set"
	fi
	if [ "$BOOTLOADER" == "GRUB" ]; then
		check_kernel_option_bootdegraded
	fi
	echo "BOOTLOADER=$BOOTLOADER" >> $VARSFILE
	echo "GRUBNAME=$GRUBNAME" >> $VARSFILE
	echo -e "GRUB_VERSION=\"$GRUB_VERSION\"" >> $VARSFILE
	echo "GRUB_INSTALL=$GRUB_INSTALL" >> $VARSFILE
	echo "MENULST=$MENULST" >> $VARSFILE
	if [ -f ${MENULST_EXTRA1} ]; then
		echo "MENULST_EXTRA1=${MENULST_EXTRA1}" >> $VARSFILE
	fi
	echo "GRUB2_CFG=$GRUB2_CFG" >> $VARSFILE
	echo "GRUB2_MKCONFIG=$GRUB2_MKCONFIG" >> $VARSFILE
	echo -e "LILO_VERSION=\"$LILO_VERSION\"" >> $VARSFILE
}



create_grub1_conf() {	# create grub 1 configuration file
	"cp" -pf $MENULST $NEWMENULST	# copy menu.lst
	echo "# $MENULST generated by $PROGRAM_NAME Ver: $VERSION" > $NEWMENULST_MD
	cat $MENULST >> $NEWMENULST_MD
	local vg=""
	local new_value=""
	local dev_0=""
	local dev_1=""
	ROOT_FS_MD=""
	local modified=""
	local OLD_ROOT=$(cat /proc/cmdline | sed 's/.*root=//g'| awk '{print $1}')	# root="  "
	local temp_DISK_DB
	if [ $BOOTP_MODE -eq 1 ]; then
		temp_DISK_DB=$DISK_DB_VIRTUAL
	else
		temp_DISK_DB=$DISK_DB
	fi
	for i in $(cat /proc/cmdline)
	do
		### checking all possible devices after a "=" sign, and change then to a new md device
		### this is usefull for other items (e.g.: "resume=")
		### if they are not a device, go on to the next item
		### if new device is equal to the old one, skip the changes 		
		if (echo $i | grep -q '='); then
			dev_0=$(echo $i | cut -d'=' -f2- | sed "s/swap://g")
			if ! (is_device $dev_0); then
				continue
			fi
			dev_1=$(realdev $dev_0)
			if [ $? -ne 0 ]; then
				continue	# when dev_0 is not a device get next item
			fi
			if (check_if_dev_is_lvm $dev_0); then
				vg="$(lvs --noheadings $dev_0 | awk '{print $2}')"
				new_value="${vg}${RAID_EXT}"
			fi
		else
			continue
		fi

		if [ -z "$vg" ]; then	# if not a lvm device
			n_boot=$(echo $dev_1 | sed 's/\/dev\/[hs]d.//g')
			if [ $BOOTP_MODE -eq 1 ]; then
				# change dev_1 to the new devpartition in virtual disk
				mmp=$(awk -v n=$n_boot '$1==n {print $6}' $DISK_DB)	# get mountpoint from original disk
				if [ "$mmp" == "#" ]; then # must be a swap partition used in resume= kernel option
					n_boot=$(awk '$4=="swap" {print $1}' $DISK_DB_VIRTUAL)
				else
					n_boot=$(awk -v mmp=$mmp '$6==mmp {print $1}' $DISK_DB_VIRTUAL)	# relate it to the virtual disk
				fi
				dev_1="$(echo $dev_1 | sed 's/[0-9]*//g')${n_boot}"	# change dev_1 to the new name based in partition number
			fi
			mdnumber=$(awk '$1 == "'"$n_boot"'" {print $7}' $temp_DISK_DB)
			if [ $mdnumber -ge 0 ]; then
				new_value="/dev/md${mdnumber}"
			else
				new_value="$dev_1"	# if device has not a corresponding mdX, save the same device with name /dev/sdXN
			fi

			local root_pf=$DB_DIR/rootp
			echo "$new_value" | sed s'/\//\\\//'g > $root_pf	# this kludge is needed to add slashes to the string
			local new_value_slashed=$(cat $root_pf)				# to be used later in a sed command : same as $md_boot
			rm -f $root_pf
			echo $dev_0 | sed s'/\//\\\//'g > $root_pf
			local dev_0_slashed=$(cat $root_pf)
			rm -f $root_pf
		fi
		if [ "$OLD_ROOT" == "$dev_0" ]; then	# if we are checking the rootfs, new ROOT_FS_MD must get the new device
			if [ -n "$vg" ]; then
				ROOT_FS_MD=$(echo "$OLD_ROOT" | sed "s/$vg/$new_value/g")
			else
				ROOT_FS_MD="$new_value"
			fi
		fi
		if [ "$new_value" == "$dev_0" ]; then
			continue	# if the device is the same, don't substitute it
		fi
		if (echo "$modified" | grep -q $new_value); then	# if new_value has been already substituted, don't do it again
			continue
		fi
		if [ -z "$vg" ]; then	# if there is a mdraid array or a volgroupname, substitute in grub.conf
#			if [ "$BOOTLOADER" == "LILO" ] && (echo $dev_0 | grep -q "^[0-9][0-9][0-9]$"); then		# in this case, lilo.conf can have both device types.
			if [ "$BOOTLOADER" == "LILO" ]; then
				sed -i.tmp s"/^\([ \t]*root[ ]*=\).*/\1 $new_value_slashed/"g $NEWMENULST_MD	
				sed -i.tmp "/^[ \t]*append/s/$dev_0_slashed/$new_value_slashed/"g $NEWMENULST_MD
			else
				sed -i.tmp "/^[ \t]*kernel/s/$dev_0_slashed/$new_value_slashed/"g $NEWMENULST_MD
			fi
		else
			sed -i.tmp "/^[ \t]*kernel/s/$vg/$new_value/"g $NEWMENULST_MD
		fi
		modified="$modified $new_value"
	done
	add_grub_devtype_to_db "$OLD_ROOT"	# save type name in db	
	echo "ROOT_FS_MD=$ROOT_FS_MD" >> $VARSFILE
	>$NEWMENULST_MD.tmp
	while read menugr
	do
		if [ "$BOOTLOADER" == "GRUB" ] && (echo "$menugr" | grep -q ^"[[:blank:]]*kernel"); then	### the menugr starts with "kernel"	
			menugr1=$(change_kernel_options "$menugr")	# this function is needed to change kernel options if needed
			if [ $BOOTP_MODE -eq 1 ]; then
				menugr1=$(echo "$menugr1" | sed 's/\/boot//g')
			fi
			echo "$menugr1" >> $NEWMENULST_MD.tmp
		elif [ "$BOOTLOADER" == "LILO" ] && (echo "$menugr" | grep -q ^"[[:blank:]]*boot[ ]*="); then
			dv=$(echo $menugr | awk '{print $2}')
			md1=$(awk '$6 == "/boot" {print $7}' $temp_DISK_DB)
			local ndev=""
			if [ -n "$md1" ]; then
				if [ $md1 -ge 0 ]; then
					ndev="/dev/md${md1}"
				fi
			else
				md1=$(awk '$6 == "/" {print $7}' $temp_DISK_DB)
				if [ $md1 -ge 0 ]; then
					ndev="/dev/md${md1}"
				fi
			fi	
			if [ -n "$ndev" ]; then
				echo "boot = ${ndev}" >> $NEWMENULST_MD.tmp
				# next line should be:  "raid-extra-boot = ${DISK[0]},${DISK[1]}..."
				# but we don't want this boot to be writen to the first disk.
				# only in step 3!
				# We have to change this line later in step 3 (install_bootloader_step3())
				local rebdisks=""
				for (( z=1; z <= ${LASTDISK}; z++ ))
				do
					if [ -z "$rebdisks" ]; then
						rebdisks="${DISK[$z]}"
					else
						rebdisks="${rebdisks},${DISK[$z]}"
					fi
				done
				echo "raid-extra-boot = ${rebdisks}" >>$NEWMENULST_MD.tmp
			else
				echo "$menugr" >> $NEWMENULST_MD.tmp
			fi
		else
			# when bootp_mode change (hdx,y) and remove /boot from the path
			if [ "$BOOTLOADER" == "GRUB" ] && [ $BOOTP_MODE -eq 1 ]; then
				echo "$menugr"  | grep -q -e ^"[[:blank:]]*root" -e ^"[[:blank:]]*gfxmenu" -e ^"[[:blank:]]*splashimage="
				if [ $? -eq 0 ]; then
					echo "$menugr" |  grep -q "(hd[0-9]\,[0-9])"	# change (hdX,Y) if ot exists
					if [ $? -eq 0 ]; then
						o_root=$(echo "$menugr" | sed "s/.*\((hd.*)\).*/\1/g")
						n_root="(hd0,0)"	# if BOOTP_MODE=1 this is always (hd0,0)
						menugr=$(echo "$menugr" | sed "s/$o_root/$n_root/g")
					fi
				fi
				# change "initrd /boot/initrd..." to "initrd /initrd..."
				echo "$menugr" | grep -q -e ^"[[:blank:]]*initrd" -e ^"[[:blank:]]*gfxmenu" -e ^"[[:blank:]]*splashimage="
				if [ $? -eq 0 ]; then
					menugr=$(echo "$menugr" | sed 's/\/boot//g')
				fi
			fi
			### FIXME check the way to do in LILO (not sure if it is working)

			# add the other lines
			echo "$menugr" >> $NEWMENULST_MD.tmp
		fi	
	done < $NEWMENULST_MD	

	### in LILO add or change initrd =
	if [ "$BOOTLOADER" == "LILO" ]; then
		for i in $(ls ${TMPLILOS}[0-9]*.txt)
		do
			if grep ^"[[:blank:]]*image" $i | grep -q "/boot/vmlinuz" ; then
				"mv" -f $NEWMENULST_MD.tmp $NEWMENULST_MD.tmp0
				if ! grep -q ^"[[:blank:]]*initrd" $i ; then
					# add a initrd
					
					while read liloinitr
					do
						echo "$liloinitr" >> $NEWMENULST_MD.tmp
						if echo "$liloinitr" | grep ^"[[:blank:]]*image" | grep -q "/boot/vmlinuz" ; then
							echo "initrd = /boot/initrd.gz" >> $NEWMENULST_MD.tmp
						fi
					done < $NEWMENULST_MD.tmp0
				else
					while read liloinitr1
					do
						if echo "$liloinitr1" | grep -q ^"[[:blank:]]*initrd" ; then
							echo "initrd = /boot/initrd.gz" >> $NEWMENULST_MD.tmp
						else
							echo "$liloinitr1" >> $NEWMENULST_MD.tmp
						fi
					done < $NEWMENULST_MD.tmp0
				fi
				"mv" -f $NEWMENULST_MD.tmp $NEWMENULST_MD
			fi
		done
		
	elif [ "$BOOTLOADER" == "GRUB" ]; then
		if [ "$GRUBNAME" == "1" ]; then
			local default1=$(grep ^"[[:blank:]]*default" ${TMPGRUBS}-1.txt | awk '{print $2}')
			default1=${default1:=0}
			if ! grep -q ^"[[:blank:]]*initrd" ${TMPGRUBS}${default1}.txt  ; then
				"mv" -f $NEWMENULST_MD.tmp $NEWMENULST_MD.tmp0
				while read grubinitr
				do
					echo "$grubinitr" >> $NEWMENULST_MD.tmp
					if echo "$grubinitr" | grep -q ^"[[:blank:]]*kernel" ; then
#						if [ "$MKINITRD" == "genkernel" ]; then	
#							echo "initrd $GENKERNEL_INITRD_NAME" >> $NEWMENULST_MD.tmp
#						fi
						echo "initrd ${vInitrd}" >> $NEWMENULST_MD.tmp
					fi
				done < $NEWMENULST_MD.tmp0
				
			fi
		fi
	fi
	"mv" -f $NEWMENULST_MD.tmp $NEWMENULST_MD
}


create_grub1_device_map() {		# create Grub1 device.map
	# this script creates a new device.map file.
	# Grub-install in grub1 has some issues in some distros
	# so, it's better to create device.map file using our own script
	# I hope I'm not wrong!!!!
	device_map=/boot/grub/device.map
	if ! [ -f $device_map ]; then
		device_map1=$(find /boot -name device.map | head -n1)
		if [ -n "$device_map1" ]; then
			device_map=$device_map1
		fi
	fi
	n=0
	>$TEMP/device.map.tmp
		
	for i in $(list_disks)
	do
		echo -e "(hd${n})\t/dev/${i}" >> $TEMP/device.map.tmp
		n=$((n+1))
	done
	if [ $STEP -eq 3 ]; then
		"mv" -f $TEMP/device.map.tmp ${device_map}
	else
		"mv" ${MOUNTPOINT}${device_map} ${MOUNTPOINT}${device_map}.beforeraider
		"mv" -f $TEMP/device.map.tmp ${MOUNTPOINT}${device_map}
	fi
	echo $device_map
}


create_grub1_run() {		# Install Grub1 in new disks
	device_map=$1
	local disknew
	local disknew_root=$(get_partboot)
	echo "{" > $GRUB1_RUN_SCRIPT
	echo "grub --device-map=${device_map} --batch << TEXT" >> $GRUB1_RUN_SCRIPT
	for ((j=1; j < ${#DISK[@]}; j++))
	do	
		disknew=$(awk -v nd="${DISK[$j]}" '$2 == nd {print $1}' ${MOUNTPOINT}${device_map} | sed s"/[\(\)]//"g)
		echo "root ($disknew,$disknew_root)" >> $GRUB1_RUN_SCRIPT
		echo "setup ($disknew)" >> $GRUB1_RUN_SCRIPT
	done
	echo "quit" >> $GRUB1_RUN_SCRIPT
	echo "TEXT" >> $GRUB1_RUN_SCRIPT
	echo "}  | tee -a ${GRUBLILOLOG}" >> $GRUB1_RUN_SCRIPT
}

create_grub1_run_step3() {	# install grub 1 during step 3
	local device_map=$1
	local disknew=$(awk -v nd="${DISK[${LASTDISK}]}" '$2 == nd {print $1}' ${device_map} | sed s"/[\(\)]//"g)
	local disknew_root=$(get_partboot)
	{
	grub --device-map=${device_map} --batch << TEXT
	root ($disknew,$disknew_root)
	setup ($disknew)
	quit
TEXT
	} | tee ${GRUBLILOLOG}
}

create_grub2_conf() {		# create GRUB2 configuration file 
	# check GRUB_CMDLINE_LINUX parameters and change lvm device names if needed
	local temp_DISK_DB
	if [ $BOOTP_MODE -eq 1 ]; then
		temp_DISK_DB=$DISK_DB_VIRTUAL
	else
		temp_DISK_DB=$DISK_DB
	fi
	"cp" -pf $MENULST $NEWMENULST	# copy menu.lst
	echo "# $MENULST generated by $PROGRAM_NAME Ver: $VERSION" > $NEWMENULST_MD
	cat $NEWMENULST >> $NEWMENULST_MD
	if [ -f $MENULST_EXTRA1 ]; then
		"cp" -pf $MENULST_EXTRA1 $NEWMENULST_MD_EXTRA1
	fi
	
	local OLD_ROOT=$(cat /proc/cmdline | sed 's/.*root=//g'| awk '{print $1}')	# root="  "
	for i in $(cat /proc/cmdline)
	do
		if (echo $i | grep -q 'root='); then
			dev_0=$(echo $i | cut -d'=' -f2-)
			if (echo $dev_0 | grep -q -e ^"UUID=" -e ^"LABEL=" -e ^"/dev"); then
				dev_1=$(realdev $dev_0)
				if (check_if_dev_is_lvm $dev_0); then
					vg="$(lvs --noheadings $dev_0 | awk '{print $2}')"
					new_value="${vg}${RAID_EXT}"
				fi
			else
				continue
			fi

			if [ -z "$vg" ]; then	# if not a lvm device
				n_boot=$(echo $dev_1 | sed 's/\/dev\/[hs]d.//g')
				mdnumber=$(awk '$1 == "'"$n_boot"'" {print $7}' $temp_DISK_DB)
				if [ $mdnumber -ge 0 ]; then
					new_value="/dev/md${mdnumber}"
				else
					new_value="$dev_1"	# if device has not a corresponding mdX, save the same device with name /dev/sdXN
				fi
				local root_pf=$DB_DIR/rootp
				echo "$new_value" | sed s'/\//\\\//'g > $root_pf	# this kludge is needed to add slashes to the string
				local new_value_slashed=$(cat $root_pf)				# to be used later in a sed command : same as $md_boot
				rm -f $root_pf
				echo $dev_0 | sed s'/\//\\\//'g > $root_pf
				local dev_0_slashed=$(cat $root_pf)
				rm -f $root_pf
			fi
			if [ "$OLD_ROOT" == "$dev_0" ]; then
				ROOT_FS_MD="$new_value"
			fi
			break
		else
			continue
		fi
	done

	if [ -z "$vg" ]; then
		NEW_ROOT=$(echo $OLD_ROOT | sed s"/$dev_0_slashed/$new_value_slashed/"g)
	else
		NEW_ROOT=$(echo $OLD_ROOT | sed s"/$vg/$new_value/"g)
	fi
	
	if [ -f ${MENULST_EXTRA1} ]; then	# used by Sabayion
		FILE_MENU=${NEWMENULST_MD_EXTRA1}
	else
		FILE_MENU=${NEWMENULST_MD}
	fi
	while read menugr
	do
		if (echo "$menugr" | grep -q ^"GRUB_CMDLINE_LINUX"); then	### check GRUB_CMDLINE_LINUX and GRUB_COMDLINE_LINUX_DEFAULT
			menugr=$(echo "$menugr" | sed -e "s/=\"/=\" /g" -e "s/\"$/ \"/g")	# insert one more space in the beginning and in the end of the string
			if ! [ -z "$vg" ]; then
				menugr=$(echo "$menugr" | sed s"/$vg/$new_value/"g)
			else
				menugr=$(echo "$menugr" | sed s"/$dev_0_slashed/$new_value_slashed/"g)
			fi

			menugr1=$(change_kernel_options "$menugr")	# this function is needed to change kernel options if needed	
			menugr1=$(echo "$menugr1" | sed -e "s/=\" /=\"/g" -e "s/ \"$/\"/g")
			echo "$menugr1" >> ${FILE_MENU}.tmp
		else
			echo "$menugr" >> ${FILE_MENU}.tmp
		fi	
	done < ${FILE_MENU}
	"mv" -f ${FILE_MENU}.tmp ${FILE_MENU}
}


create_lilo_conf() {	# create lilo configuration file
	create_grub1_conf	# use same grub1 function which supports lilo.
}

get_grub1_items() {		# parse grub1 items
	# find pathname of grub.conf
	# get variables:
	# root
	# kernel	name root= options
	# initrd	name
	
	for a in $GRUB_CONFIG_FILES; do
		if [ -e "$a" ]; then
			MENULST=$a
			break
		fi
	done
	
	if [ -z "$MENULST" ]; then
		# if grunb.conf was not found with known path's check another way in /boot path
		for a in $GRUB_BASENAMES; do
			MENULST=$(find /boot -name $a)
			if ! [ -z "$MENULST" ]; then
				break
			fi
		done
		if [ -z "$MENULST" ]; then
			# try in / path. (a longer search)
			for a in $GRUB_BASENAMES; do
				MENULST=$(find / -name $a)
				if ! [ -z "$MENULST" ]; then
					break
				fi
			done
		fi
	fi
	if [ -z "$MENULST" ]; then
		printing "Grub configuration file not found!"
		exit 1
	else
		MENULST=$(readlink -f $MENULST)
		printing "Grub configuration file found in $MENULST"
	fi	
	####   get values from grub configuration file
	####   get field separator
	if (grep ^default $MENULST | grep -q "="); then
	    separator="="
	else
	    separator=" "
	fi

	vBoot_menu_item=$(grep ^default $MENULST | awk -v sep="$separator" 'BEGIN {FS=sep} ; {print $2}')
	if [ -z "$vBoot_menu_item" ]; then
		vBoot_menu_item=0
	fi
	# split grub.conf in to files name "grubsN.txt" (ex: grubs-1.txt grubs0.txt grubs1.txt)
	# and remove commented lines 
	sed -e '/^#/'d -e '/^$/'d $MENULST | awk 'BEGIN {n=-1} /^title/{n++}{print > "'"$TMPGRUBS"'" n ".txt" }'
	# now, based on vBoot_menu_item (the one which is selected by default)
	# get the file needed and read vInitrd
	local qoptions=$(find ${TEMP} -name "grubs[0-9]*.txt" | wc -l)
	if [ ${vBoot_menu_item} -gt ${qoptions} ]; then
		printdivision
		fatal_error "Error in $MENULST:"
		echoing "\"default=${vBoot_menu_item}\" has a wrong value."
		echoing "Edit $MENULST and change to \"default=0\" before running raider"
		exit 1
	fi
	vInitrd=""
	while read bootv
	do
		if (echo $bootv | grep -q ^[[:blank:]]*initrd); then
			vInitrd=$(echo $bootv | sed -e 's/^[ |\t]*initrd[ |\t]*//g' -e 's/ *$//g')
			#continue
			break
		fi
	done < ${TMPGRUBS}${vBoot_menu_item}.txt 
	if [ -n "$vInitrd" ]; then
		vInitrd="/boot/$(basename $(echo "${vInitrd}" | cut -d'/' -f2-))"	# remove other info from the line
		# vInitrd sometimes is a softlink named in grub config
		# but we must have the real name to create the new initramfs 
		vInitrd=$(readlink -e ${vInitrd})
	fi
	vKroot=$(head -n1 /proc/cmdline |  sed -e s'/.*root=//'g -e s'/ .*//'g)
	vResume=""
	while read bootv1
	do
		if (echo $bootv1 | grep -q ^[[:blank:]]*kernel); then
			vResume=$(echo $bootv1 | grep "resume=" | sed -e s'/.*resume=//'g -e s'/ .*//'g)
			if [ -n "$vResume" ]; then
				break
			fi
		fi
	done < ${TMPGRUBS}${vBoot_menu_item}.txt 
	if [ -z "$vResume" ]; then
		vrmess="There is no \"resume=\" kernel option"
	else
		if [ $NO_SWAPRAIDER -eq 0 ]; then
			#vrmess="There is a \"resume=\" kernel option: resume=${vResume}"
			vrmess="There is a \"resume=\" kernel option: resume=${vResume}. Option -s will be used by default"
			SWAPRAIDER_MODE=1	# turn swapraider on	
		else
			vrmess="There is a \"resume=\" kernel option: resume=${vResume}. This device will not be a raid device"
			SWAPRAIDER_MODE=0
		fi
	fi
	logging "vKroot: $vKroot"
	logging "vInitrd: $vInitrd"
	logging "$vrmess"
}


get_grub2_items() {		# parse grub 2 items

	for a in $GRUB2_CONFIG_FILES; do
		if [ -e "$a" ]; then
			MENULST=$a
			break
		fi
	done
	if [ -z "$MENULST" ]; then
		fatal_error "Grub 2 configuration file not found!"
		exit 1
	fi		
	for a in $GRUB2_CFG_FILES; do
		if [ -e "$a" ]; then
			GRUB2_CFG=$a
			break
		fi
	done
	if [ -z "$GRUB2_CFG" ]; then
		fatal_error "Grub 2 configuration file not found!"
		exit 1
	fi
	for a in $GRUB2_MKCONFIG_FILES; do
		if (type "$a" >/dev/null 2>&1); then
			GRUB2_MKCONFIG=$(type -p $a)
			break
		fi
	done
	if [ -z "$GRUB2_MKCONFIG" ]; then
		fatal_error "grub-mkconfig does not exist"
		exit 1
	fi
	# get the first vInitrd found in menu
	vInitrd=$(grep -m1 "^[[:blank:]]*initrd" $GRUB2_CFG | sed -e 's/^[ |\t]*initrd[ |\t]*//g' -e 's/ *$//g')
	if [ -n "$vInitrd" ]; then
		vInitrd="/boot/$(basename $(echo "${vInitrd}" | cut -d'/' -f2-))"	# remove other info from the line (like (hd1,0)
		vInitrd=$(readlink -e ${vInitrd})
	fi
	# root can be parsed from cmdline, because system must be booting from the right device
	vKroot=$(head -n1 /proc/cmdline |  sed -e s'/.*root=//'g -e s'/ .*//'g)
	# is there a resume= option?
	vResume=$(grep -m1 "^[[:blank:]]*linux" $GRUB2_CFG | grep "resume=" | sed -e s'/.*resume=//'g -e s'/ .*//'g)
	if [ -z "$vResume" ]; then
		vrmess="There is no \"resume=\" kernel option"
	else
		if [ $NO_SWAPRAIDER -eq 0 ]; then
			vrmess="There is a \"resume=\" kernel option: resume=${vResume}. Option -s will be used by default"
			SWAPRAIDER_MODE=1	# turn swapraider on
		else
			vrmess="There is a \"resume=\" kernel option: resume=${vResume}. This device will not be a raid device"
			SWAPRAIDER_MODE=0
		fi
	fi
	logging "vKroot: $vKroot"
	logging "vInitrd: $vInitrd"
	logging "$vrmess"
}


get_kernel_options() {		# parse kernel options 
	kop=$(cat /proc/cmdline)
	vKroot=$(echo $kop | sed -e s'/.*root=//'g -e s'/ .*//'g)
	v_kroot=$(echo $vKroot | sed s'/\//\\\//g')
	vKoptions=$(echo $kop | sed s"/.*$v_kroot //"g)
	echo "$vKoptions"
}

get_lilo_items() {			# parse lilo items
	for a in $LILO_CONFIG_FILES; do
		if [ -e "$a" ]; then
			MENULST=$a
			break
		fi
	done
	if [ -z "$MENULST" ]; then
		printing "LILO configuration file not found!"
		exit 1
	else
		printing "LILO configuration file found in $MENULST"
	fi
	local rootdev=$(head -n1 /proc/cmdline | sed -e s'/.*root=//'g -e s'/ .*//'g )
	
	if [ $(devtype $rootdev) == 'numeric' ]; then
		rootdev1=$(numeric2dev $rootdev)
	fi
	sed -e '/^#/'d -e '/^$/'d $MENULST | awk 'BEGIN {n=-1} /^image[ ]*/{n++}{print > "'"$TMPLILOS"'" n ".txt" }'	# create lilo.conf in small files
	
	for i in $(ls ${TMPLILOS}[0-9]*.txt)
	do
		while read liloln
		do
			vKroot=""
			vInitrd=""

			if (echo $liloln | grep -q "initrd[ ]*="); then
				vInitrd=$(echo $liloln | sed -e 's/^initrd[ ]*=[ ]*//g' -e 's/ *$//g')
			fi
			if (echo $liloln | grep -q "root[ ]*="); then
				vRoot=$(echo $liloln | sed -e 's/^root[ ]*=[ ]*//g' -e 's/ *$//g'  )
				if [ "$vRoot" == "$rootdev1" -o "$vRoot" == "$rootdev" ]; then
					vKroot=$vRoot
				fi
			fi


			if ! [ -z "$vKroot" ]; then
				break
			fi
		done < $i
	done
	
	vResume=""
	for i in $(ls ${TMPLILOS}[0-9]*.txt)
	do
		while read liloln2
		do	
			if (echo $liloln2 | grep "append[ ]*=" | grep -q "resume="); then
				vResume=$(echo $liloln | sed -e "s/.*resume=//" -e "s/ .*//g")
			fi	
			if [ -n "$vResume" ]; then
				break
			fi
		done < $i
	done		
	if [ -z "$vResume" ]; then
		vrmess="There is no \"resume=\" kernel option"
	else
		if [ $NO_SWAPRAIDER -eq 0 ]; then
	#		vrmess="There is a \"resume=\" kernel option: resume=${vResume}"
			vrmess="There is a \"resume=\" kernel option: resume=${vResume}. Option -s will be used by default"
			SWAPRAIDER_MODE=1	# turn swapraider on		
		else
			vrmess="There is a \"resume=\" kernel option: resume=${vResume}. This device will not be a raid device"
			SWAPRAIDER_MODE=0			
		fi
	fi	
	logging "vKroot: $vKroot"
	logging "vInitrd: $vInitrd"	# this can be empty
	logging "$vrmess"	
}

get_partboot() {		# parse partition number where /boot directory resides
	local temp_DISK_DB
	if [ $BOOTP_MODE -eq 1 ]; then
		temp_DISK_DB=$DISK_DB_VIRTUAL
	else
		temp_DISK_DB=$DISK_DB
	fi
	numboot=$(awk '$6 == "/boot" {print $1}' $temp_DISK_DB)
	if [ -z $numboot ]; then
		numboot=$(awk '$6 == "/" {print $1}' $temp_DISK_DB)
	fi
	numboot=$((numboot-1))		# to support grub syntax partition. (e.g. hd0,0 = /dev/sda1)
	echo $numboot
}

install_bootloader_step3() {	# install bootloader in the new disk during step 3
	if [ "${BOOTLOADER}" == "GRUB" ]; then
		if [ "${GRUBNAME}" == "2" ]; then
			printing "Install Grub 2 in ${DISK[${LASTDISK}]}"
			$GRUB_INSTALL --no-floppy --recheck ${DISK[${LASTDISK}]}
			res=$?
			return ${res}
		elif [ "${GRUBNAME}" == "1" ]; then
			local devmap1=$(create_grub1_device_map)
			printing "Install Grub 1 in ${DISK[${LASTDISK}]}"
			create_grub1_run_step3 $devmap1
			if (grep -q ^Error_chroot ${GRUBLILOLOG}); then
				return 1
			fi
		fi
	elif [ "${BOOTLOADER}" == "LILO" ]; then
		# change raid-extra-boot=/dev/sdX,/dev/sdY... (all disks to install bootloader
		local rebdisks=""
		for (( a=0; a <= ${LASTDISK} ; a++ ))
		do
			if [ -z "$rebdisks" ]; then
				rebdisks="${DISK[$a]}"
			else
				rebdisks="${rebdisks},${DISK[$a]}"
			fi
		done
		printing "Install Lilo in disk ${rebdisks}"
		echo "${rebdisks}" | sed s'/\//\\\//'g >/tmp/raider_ib_$$.tmp # no space (only "," between devices)
		local reb=$(cat /tmp/raider_ib_$$.tmp)
		"rm" -f /tmp/raider_ib_$$.tmp
		sed -i.tmp s"/\(raid-extra-boot[ ]*=\).*/\1 $reb/"g $MENULST
		"rm" -f ${MENULST}.tmp
		lilo -H -v
		res=$?
		return ${res}
	fi
}

is_boot_manager_in_mbr() {	# check if there is a boot manager embedded in mbr
	dd if=${DISK[0]} bs=512 count=1 of=$MBRFILE 2>/dev/null
	mbr_sign=$(hexdump -v -s 510 -n 2 -e '1/1 "%02X"' $MBRFILE)
	"rm" -f $MBRFILE
	if [ "$mbr_sign" == "55AA" ]; then
		return 0
	fi
	return 255	# if no boot manager in mbr
}

set_kernel_option_grub1() {		# include new option in grub1 kernel option 
	#e.g.: set_kernel_opt "bootdegraded=true" $NEWMENULST_MD
	local new_option=$1
#	local grubfile=$2
	if [ "$GRUBNAME" == "1" ]; then
		kop=$(get_kernel_options)
		if (echo $kop | grep -vq $new_option  ); then
			new_kop="$kop $new_option"
			sed -i.tmp "s/$kop/$new_kop/g" ${NEWMENULST_MD}
			"rm" -f ${NEWMENULST_MD}.tmp
		fi
	fi
}

set_kernel_option_grub2() {		# include new option in grub 2 kernel option 
	
	# e.g.: set_grub2_option bootdegraded GRUB_CMDLINE_LINUX $grub.conf-file add
	local option=$1
	local option1=$option
	local grub_variable=$2
	local grub_c=$3
	local mode=$4	# it can be "add" or "set".
	
	# check if variable is not commented
	# if it is commented, uncomment it
	# get the value of variable
	# include the new value if "add" mode.
	# change the value if "set" mode.
	
	grub_variable="${grub_variable}="	# add a sign "="
	
	if (grep -q ${grub_variable} ${grub_c}); then 	# remove any # in the beginning of line
		sed -i.tmp "s/^[ \t]*#\+\(${grub_variable}\)/\1/g" ${grub_c}
	fi
		
	if [ -n "$(grep $grub_variable ${grub_c} | sed -e "s/\"//"g -e "s/.*=//g")" ]; then	# if not empty, option will have a beginning space 
		option=" $option"
	fi

	local a=" $(grep ${grub_variable} ${grub_c} | cut -d'=' -f2- | sed 's/\"//g')"
	if [ -n "$a" ]; then
		if (echo "$a" | grep -q "${option}"); then
			return # return if value already exist
		fi
	fi

	if [ "$mode" == "add" ]; then
		if (grep -q ^${grub_variable} ${grub_c}); then
			sed -i.tmp -e "/^$grub_variable/s/\"//g" -e "/^$grub_variable/s/\($grub_variable.*$\)/\1$option/g" -e "/^$grub_variable/s/\($grub_variable\)\(.*\)/\1\"\2\"/g" ${grub_c}
			"rm" -f ${grub_c}.tmp
		else
			# if not exist in file, add it to the end of the file
			echo -e ${grub_variable}\"${option1}\" >> ${grub_c}
		fi
	elif [ "$mode" == "set" ]; then
		if (grep -q ^${grub_variable} ${grub_c}); then
			sed -i.tmp "s/^\($grub_variable\).*/\1$option1/g" ${grub_c}
			"rm" -f ${grub_c}.tmp
		else
			echo -e ${grub_variable}\"${option1}\" >> ${grub_c}
		fi
	fi

}


