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

clear_disk() {		# Clear or delete disk
	
	# e.g.: clear_disk /dev/sdb
	disk_to_clean=$1	
	check_root

	printing "Deleting $disk_to_clean"
	logging "Check if this is not the system disk"
	system_disk=$(get_system_disk)
	if ! (ls $disk_to_clean >/dev/null 2>&1 ); then
		echoing "$disk_to_clean not found"
		exit 1	
	fi
	
	if [ "$system_disk" == "$disk_to_clean" ]; then
		echoing "$disk_to_clean is the system disk. Delete is forbidden"
		exit 1
	fi
	
	if (mount | grep -q ^"$disk_to_clean"); then
		echoing "$disk_to_clean is mounted. Unable to delete"
		exit 1
	fi

	# check if there is a md device mounted
	dtc0=$(echo ${disk_to_clean} | sed 's/\/dev\///g')
	for i in $(grep "${dtc0}[0-9]\+" /proc/mdstat | awk '{print $1}')
	do
		if (mount | grep -q ^/dev/${i}); then
			echoing "Partition /dev/$i is mounted. Unmount it first"
			echoing "Unable to delete"
			exit 1
		fi
	done
	
	echoing "WARNING: ALL DATA IN ${DISK[1]} WILL BE ERASED!"
	echoing_n "Do you want to continue (yes/no)? "
	read answer
	if [ "$answer" == "yes" ]; then
		>$LOGFILE
		date +%F" "%T >> $LOGFILE
		logdivision
		delete_disk $disk_to_clean
		local retv=$?
		if [ $retv -eq 0 ]; then
			printing "$disk_to_clean erased!"
		elif [ $retv -eq 1 ]; then
			printing "$disk_to_clean not erased. Disk is already empty!"
		fi
	else
		printing "$disk_to_clean NOT erased"
	fi
}


description() {		# Display help screen
	version_info
	echo "Usage:  $PROGRAM_NAME [options] [Conversion options]"
	echo
	echo "Examples:"
	echo -e " raider -R1 sda sdb\t# convert /dev/sda single disk to a 2 disk raid1 system"
	echo -e " raider -R1\t\t# if there are only two disks, don't need to name them"
	echo -e " raider -R5 sda sdb sdc\t# convert /dev/sda single disk to a 3 disk raid5 system"
	echo -e " raider -e /dev/sdb\t# erase /dev/sdb disk"
	echo -e " raider -d\t\t# List all disks info"
	echo -e " * (devices can be named as \"/dev/sdX\" or \"sdX\" without \"/dev/\")"
	echo
	echo -e "Conversion options:"
	echo -e " -R1,  ${long_options[4]} <single_disk><d1><...> (min: 1+1 disks)"
	echo -e " -R4,  ${long_options[5]} <single_disk><d1><d2><dN><..> (min: 1+2 disks)"
	echo -e " -R5,  ${long_options[6]} <single_disk><d1><d2><dN><..> (min: 1+2 disks)"
	echo -e " -R6,  ${long_options[7]} <single_disk><d1><d2><d3><dN><..> (min: 1+3 disks)"
	echo -e " -R10, ${long_options[8]} <single_disk><d1><d2><d3><dN><..> (min: 1+3 disks)"
	echo -e "       ${long_options[12]}\t\t# Second command to complete the process after"
	echo -e "\t\t\t  swapping disks or after \"-t\" option"
	echo
	echo -e "Options:"
	echo -e " -t, ${long_options[15]}\t\t# Test -R options. Scans the system and output results"
	echo -e " -d, ${long_options[1]}\t\t# List disks, partitions, mountpoints and raid arrays"
	echo -e " -e, ${long_options[10]} <device>\t# Erase disk"
	echo -e " -V, ${long_options[0]}\t\t# Print version number"
	echo -e " -h, ${long_options[3]}\t\t# This help screen"
	echo
	echo -e "Advanced Options: (Barely used. Read the manual before use them)"
	echo -e " -s, ${long_options[2]}\t # Create a raid array combining all swap partitions"
	echo -e "\t\t\t   By default swapraider is not set, unless there is"
	echo -e "\t\t\t   a \"resume\" kernel option in the bootloader menu."
	echo -e "\t\t\t   In this case, swapraider will be set automatically."
  	echo -e " -l, ${long_options[11]} <name> # Chose another LVM Volume Group suffix name"
  	echo -e " -b, ${long_options[14]} [<size>] [<filesystem>]"
  	echo -e "\t\t\t # Change the size and filesystem of the automatic"
  	echo -e "\t\t\t   /boot partition created by raider when needed"
  	echo -e "\t\t\t   Size units in \"MB\" or \"KB\"."
  	echo -e "\t\t\t   Filesystems=ext2, ext3, ext4, xfs, jfs, reiserfs"
  	echo -e "\t\t\t   Default filesystem=ext2 and size=500MB"
}

listdevices() {		# option -d (device list)
	check_root
	local prefix
	local last_prefix
	if (echo $LANG | grep -qi utf); then
		prefix=" \xE2\x94\x9C\xE2\x94\x80\xE2\x94\x80"
		last_prefix=" \xE2\x94\x94\xE2\x94\x80\xE2\x94\x80"
	else
		prefix=" |--"
		last_prefix=' `--'
	fi
	version_info
	kernel_messages_off
	if ! [ -d $DB_DIR ]; then
		mkdir -p $DB_DIR 2>/dev/null
	fi
	if ! [ -d $TEMP ]; then
		mkdir -p $TEMP 2>/dev/null
	fi

	mount_clean

	echo "List disks:"
	for hdisk in $(awk '$4 ~ "^[hs]d[a-z]$" {print "/dev/"$4}' < <(tail -n+3 /proc/partitions) | sort)
	do
		messdisk="Disk $hdisk - $(d_info_space $hdisk) - $(d_info_name $hdisk): $(d_info_model $hdisk) - $(d_info_serial $hdisk)"
		echo -e "\n$messdisk"	
		part_table=$(parted_machine $hdisk | awk -F: 'NR==2 {print $6}')
		if [ "$part_table" == "msdos" ]; then
			p_table="MBR/msdos"
		elif [ "$part_table" == "gpt" ]; then
			p_table="GPT/GUID"
		else
			p_table=$part_table
		fi
		if [ -z "$p_table" ]; then
			echo "Partition table not found"
		else
			echo "Partition Table: $p_table"	
		fi
		np=$(dinfo_partition_quantity "$hdisk")
		n=0	
		while read infop
		do
			# if MBR/msdos
			# 1-device(/dev/sda1)  2-dos_partition_type(logical)  3-sys_partition_type(Linux)  4-size(3344MB)  
			# 5-filesystem(ext4) or md_device(/dev/md1)  6-bootflag(boot_flag)  7-mountpoint(/mnt)(swap)
			
			# if GPT
			# 1-device(/dev/sda1)  2-gpt_name_partition(PNAME)  3-sys_partition_type/flags_gpt(lvm, boot, raid) 4-size(3344MB) 
			# 5-filesystem(ext4) or md_dev(/dev/md1)  6_mountpoint(/mnt)
			
			m_npart=$(echo "$infop" | awk '{print $1}')
			type_lvm="no"
			m_device=${hdisk}${m_npart}
			m_fs_type=$(blkid -c /dev/null -s TYPE "$m_device" | sed -e "s/.*TYPE=//g" -e "s/\"//g" -e "s/[ ]*$//g")
			if [ -z "${m_fs_type}" ]; then
				m_fs_type=" "
			fi
			m_size=$(echo "$infop" | awk '{print $4}')
			if [ "$p_table" == "MBR/msdos" ]; then
				m_dos_type=$(lformat_dos_type "$infop")
				m_sys_type=$(lformat_sys_type ${hdisk} ${m_device} ${m_npart})
				if [ "$m_fs_type" == "linux_raid_member" ]; then
					nodev=$(echo $m_device | sed 's/\/dev\///')
					m_fs_type="( $(grep $nodev /proc/mdstat | cut -d' ' -f1) )"	# if raid print mdarray
				fi
				m_boot_flag=$(lformat_bootflag ${hdisk} ${m_npart})
				if [ "$m_sys_type" == "Linux LVM" ] || [ "$m_fs_type" == "LVM2_member" ]; then
					type_lvm="lvm"
					m_mountpoint="none"
				else
					m_mountpoint=$(awk -v m_device="$m_device" '$1 == m_device {print $2}' $MOUNT_CLEAN)
				fi
			else
				# GPT
				gpt_name_partition=$(lformat_gpt_name_partition ${hdisk} ${m_npart})
				flags_gpt=$(lformat_sys_type ${hdisk} ${m_device} ${m_npart})
				if [ "$m_fs_type" == "linux_raid_member" ]; then
					nodev=$(echo $m_device | sed 's/\/dev\///')
					m_fs_type="( $(grep $nodev /proc/mdstat | cut -d' ' -f1) )"	# if raid print mdarray
				fi				
				m_boot_flag=$(lformat_bootflag ${hdisk} ${m_npart})
				if ! (echo "$flags_gpt" | grep -q "lvm"); then
					m_mountpoint=$(awk -v m_device="$m_device" '$1 == m_device {print $2}' $MOUNT_CLEAN)
				else
					type_lvm="lvm"
					m_mountpoint=""
				fi
			fi
			if [ -z "${m_mountpoint}" ]; then
				if [ "$m_fs_type" == swap ]; then
					m_mountpoint="swap"
				else
					m_mountpoint="none"
				fi
			fi
			if [ "$p_table" == "MBR/msdos" ]; then
				partinf="$(rpad ${m_device} 11) $(rpad ${m_boot_flag} 5) $(rpad ${m_dos_type} 4) $(rpad "${m_sys_type}" 22) $(rpad "${m_fs_type}" 12) $(rpad ${m_size} 8) ${m_mountpoint}"
			else
				partinf="$(rpad ${m_device} 11) $(rpad ${m_boot_flag} 5) $(rpad ${gpt_name_partition} 6) $(rpad "${flags_gpt}" 20) $(rpad "${m_fs_type}" 12) $(rpad ${m_size} 8) $m_mountpoint"
				
			fi
			
			n=$((n+1))
			if [ $n -lt $np ]; then
				partinf="${prefix}${partinf}"
			else
				partinf="${last_prefix}${partinf}"
			fi
			echo -e "$partinf"
			
			if [ "$type_lvm" == "lvm" ]; then
				vg=$(pvs --noheadings $m_device 2>/dev/null | awk '{print $2}')
				if [ -z "$vg" ]; then
					continue
				fi

				while read lvdevs
				do
					realdev $lvdevs >> /tmp/lvm2p-$$
				done < <(lvs --noheadings $vg | awk '{print "/dev/"$2"/"$1}' | xargs -I {} dmsetup info -c --noheadings {} | awk -F: '{print "/dev/mapper/"$1}')
				nlvm=$(cat /tmp/lvm2p-$$ | wc -l)
				tt=0
				while read lvmread
				do
					tt=$(( tt+1 ))
					mp=$(awk -v lvmread="$lvmread" '$1 == lvmread {print $2}' $MOUNT_CLEAN.FSTAB)
					if [ "$mp" == "swap" ] || [ "$mp" == "none" ]; then
					    # get swap device from fstab, because it is absent in /proc/mounts
					    mdv=$(grep -e ^/dev -e ^"UUID=" -e ^"LABEL=" $MOUNT_CLEAN.FSTAB | awk '$3 == "swap" {print $1}')
					else
					    mdv=$(mount | grep ^/dev | awk -v mp="$mp" '$3 == mp {print $1}')	# get /dev/dm-X udevname
					    mdv=$(realdev $mdv)
					fi
					mdv_lvm=$(dm2lvm $mdv)
					fstype_l=$(blkid -c /dev/null -s TYPE "$mdv_lvm" | sed -e "s/.*TYPE=//g" -e "s/\"//g")
					if [ "${mp}" == "none" ] && [ "${fstype_l}" == "swap" ]; then
						mp="swap"
					fi
					mdv_lvm=$(dm2lvm $mdv)
					m_size=$(lvs --noheadings --units H ${mdv_lvm} | awk '{print $NF}')
					message="$(rpad ${mdv_lvm} 42) $(rpad ${fstype_l} 12) $(rpad ${m_size} 8) ${mp}" 
					if [ -z "$mdv_lvm" ]; then
						message="(device not defined in /etc/fstab)"
					fi
					if [ $tt -lt $nlvm ]; then 
						message="   ${prefix}${message}"
					else
						message="   ${last_prefix}${message}"
					fi
					echo -e "$message"
	
				done < /tmp/lvm2p-$$
				#"rm" -f /tmp/lvm2p-$$
			fi	
		done < <(env LC_ALL=C parted $hdisk print 2>/dev/null | awk '$1 ~ "^[0-9]+" {print}')
	done
	
	# check if md arrays exist
	if ! (tail -n+3 /proc/partitions | awk '{print $4}' | grep -q ^md); then
		echo 
		return
	fi

	# List RAID ARRAYS

	echo -e "\nList Raid Arrays:\n"
	for j in $(tail -n+3 /proc/partitions | awk '{print $4}' | grep ^md | sort)
	do
		mj=$j
		j="/sys/block/$j"
		level=$(head -n1 $j/md/level | awk '{print toupper($0)}')
		ndisks=$(head -n1 $j/md/raid_disks)
		mounted=$(mount | awk -v dv="/dev/$mj" '$1 == dv {print $3}')
		mtdta="($(cat $j/md/metadata_version))"
		if [ -z "${mounted}" ]; then
			mounted="none"
		fi
		#devices from array
		fsy_type=$(pvs --noheadings "/dev/$mj" 2>/dev/null | awk '{print $3}')
		if [ "$fsy_type" == "lvm2" ]; then
		    fsy_type="LVM2_member"
		else
		    fsy_type=$(blkid -c /dev/null -s TYPE "/dev/$mj" | sed -e "s/.*TYPE=//g" -e "s/\"//g" )
		fi
		cnd=0
		md_device=/dev/$(basename ${j})
		local array_size=$(cat $j/size)
		array_size=$(convert_sectors2Human $array_size "/dev/$mj")
		echo -e "$(rpad "RaidArray ${md_device} - ${level} ${mtdta}" 34) $(rpad "${fsy_type}" 9) $(rpad "${array_size}" 9) ${mounted}"

		message=""
		for devr in $(ls -d $j/md/dev-* | xargs -I {} basename {} | sed 's/dev-//g')
		do
			cnd=$((cnd+1))
			slot=$(head -n1 $j/md/dev-${devr}/slot)
			if [ -n "$message" ]; then
				message="${message} + ${devr}[${slot}]"
			else
				message="${devr}[${slot}]"
			fi
		done
		for ((a=$cnd ; a < $ndisks; a++))
		do
			message="${message} + missing"
		done
		echo -e "  :  ${message} "
		ls_lvm_raid $fsy_type $md_device
	done
	kernel_messages_on
	if [ -f "$STEP_FILE" ]; then
		STEP=$( head -n1 $STEP_FILE )
	fi
	if [ $STEP -eq 3 ]; then
		echo "(Waiting for RaidSync phase #raider --run)"
		echo
	fi
}


ls_lvm_raid() {	# list raid devices in lvm partitions
	fsy_type=$1
	md_device=$2
	
	if [ "$fsy_type" != "LVM2_member" ]; then
		return 1
	fi
	local vg=$(pvs --noheadings $md_device 2>/dev/null | awk '{print $2}')
	if [ -z "$vg" ]; then
		return 1
	fi
	while read lvdevs
	do
		realdev $lvdevs >> /tmp/lvm2p2-$$
	done < <(lvs --noheadings $vg | awk '{print "/dev/mapper/"$2"-"$1}')
	local nlvm=$(cat /tmp/lvm2p2-$$ | wc -l)
	local tt=0

	while read lvmread
	do
		tt=$(( tt+1 ))
		local mp=$(awk -v lvmread="$lvmread" '$1 == lvmread {print $2}' $MOUNT_CLEAN.FSTAB)
		#if [ -z "$mp" ]; then
		#	continue
		#fi
		local mdv
		if [ -z "$mp" ]; then
		    mdv=$(dm2lvm $lvmread)
		elif [ $mp == swap ] || [ $mp == none ]; then
			# get swap mountpoint from fstab, because it is absent in /proc/mounts
			mdv=$(grep -e ^/dev -e ^"UUID=" -e ^"LABEL=" $FSTAB | awk '$3 == "swap" {print $1}')
		else
			mdv=$(mount | grep ^/dev | awk -v mp="$mp" '$3 == mp {print $1}')	# get /dev/dm-X udevname
		fi
		local fstype_l=$(blkid -c /dev/null -s TYPE "$mdv" | sed -e "s/.*TYPE=//g" -e "s/\"//g")
		if [ ${mp} == none ] && [ ${fstype_l} == swap ]; then
			mp="swap"
		fi
		local m_size=$(lvs --noheadings --units H ${mdv} | awk '{print $NF}')
		if [ -z "$mp" ]; then
		    mp="none"
		fi
		mdv=$(dev2devtype $mdv mapper)
		local message="$(rpad ${mdv} 40) $(rpad ${fstype_l} 9) $(rpad ${m_size} 10) ${mp}" 
		if [ $tt -lt $nlvm ]; then 
			message=" ${prefix}${message}"
		else
			message=" ${last_prefix}${message}"
		fi
		echo -e "$message"
	done < /tmp/lvm2p2-$$
	#"rm" -f /tmp/lvm2p2-$$
}


raider_run() {		# option --run
	step_scan
	if [ $STEP -eq 2 ]; then
		check_root
		go_step_2
	elif [ $STEP -eq 3 ]; then	# when booting from new disks with raid arrays, they wait for step 3
		check_root
		go_step_3
	elif [ $STEP -eq 0 ]; then	# if in the original disk, after creating raid arrays in the new disks.
		echoing "Oops!! You have completed BuildRaid phase."
		echoing "Change disks first, before running \"raider --run\""
		exit 1
	else
		echoing "FATAL ERROR: Raider is not able to continue"
		echoing "You need to have a successful -R option first"
		exit 1
	fi

}




