#!/bin/bash
##################################################################
#   raider - converts a single disk linux system in to a software raid system
#            with two or mor disks
# 
#   Copyright (C) 2012 M.Carreira - Under GNU General Public License
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.

#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.

#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
##################################################################

all_parameters=$*
DEBUG_MODE=0
if (echo "$all_parameters" | grep -q '\-\-debug'); then	# switch debug mode before everything
	DEBUG_MODE=1
	set -x
fi
if [ $BASH_VERSINFO -lt 3 ]; then	# bash version must be tested in the beginning
	echo "Bash version is ${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}. You need version 3 or higher"
	exit 1
fi

###################################################
RAIDER_REV=149
VERSION=0.13.2
#PROGRAM_NAME="${0##*/}"	# The program name
#RAIDER_LIB=/usr/lib/raider
# module scripts
subdirfunctions=${RAIDER_LIB}
GLOBALVARS=${subdirfunctions}/globalvars			# global variables
PRINTFUNCTIONS=${subdirfunctions}/printfunctions	# all print functions
DEVICEFUNCTIONS=${subdirfunctions}/devices			# all device functions
OPTIONSFILE=${subdirfunctions}/options				# calling raider [ -options ] (excluding single2raid1)
BARFORMAT=${subdirfunctions}/barformat
SINGLETORAID=${subdirfunctions}/single2raid
GETDISK=${subdirfunctions}/getdisk					# disk functions
GRUBFUNCTIONS=${subdirfunctions}/grubfunctions		# grub functions
LINUXDISTRO=${subdirfunctions}/linuxdistro			# linux distro information (name, version,...)
STEP2=${subdirfunctions}/step2						# run step 2
STEP3=${subdirfunctions}/step3						# run step 3
PARTITIONCOPY=${subdirfunctions}/partitioncopy		# copy partitions functions 
PROGBAR=${subdirfunctions}/progbar					# progress bar functions 
MAINFUNCTIONS=${subdirfunctions}/mainfunctions		# all other functions
PTCLONE=${subdirfunctions}/ptclone					# function to clone disk partitions
RESYNCMD=${subdirfunctions}/resyncmd				# a subsitute for watch cat /proc/mdstat
CONVERTER=${subdirfunctions}/converter				# disk size unit conversion functions
BOOTCREATOR=${subdirfunctions}/bootcreator			# functions to create a new boot partition
###################################################

. $GLOBALVARS
. $MAINFUNCTIONS
. $OPTIONSFILE
. $BARFORMAT
. $DEVICEFUNCTIONS
. $PRINTFUNCTIONS
. $GETDISK
. $SINGLETORAID
. $LINUXDISTRO
. $GRUBFUNCTIONS
. $STEP2
. $STEP3
. $PARTITIONCOPY
. $PROGBAR
. $PTCLONE
. $RESYNCMD
. $CONVERTER
. $BOOTCREATOR

fill_tempfiles_variables	# set global variables with default

declare -a long_options

long_options[0]="--version"						# -V
long_options[1]="--disklist"					# -d
long_options[2]="--swapraider"					# -s
long_options[3]="--help"						# -h
long_options[4]="--single-to-raid1"				# -R1 (mirror or raid1)
long_options[5]="--single-to-raid4"				# -R4 (raid4)
long_options[6]="--single-to-raid5"				# -R5 (raid5)
long_options[7]="--single-to-raid6"				# -R6 (raid6)
long_options[8]="--single-to-raid10"			# -R10 (raid10)
long_options[9]="--raid-to-single"				# -S					# not implemented yet
long_options[10]="--erase"						# -e
long_options[11]="--lvm-suffix"					# -l
long_options[12]="--run"						# --run
long_options[13]="--debug"						# debug mode
long_options[14]="--boot"						# -b 
long_options[15]="--test"						# --test
long_options[16]="--version-number"				# --version-number
long_options[17]="--revision-number"			# --revision-number
long_options[18]="--no-swapraider"				# inverse of --swapraider

# OPTIND = index of next argument
# OPTARG = option arguments

# looking at the options
while getopts ":R:Ve:l:dtb:swh" option; do
	  case $option in
	  	R)
			Roption="$OPTARG"
			if [ "$Roption" == "1" ]; then
				OPTION_TYPE="SINGLE_TO_RAID1"
			elif [ "$Roption" == "4" ]; then
				OPTION_TYPE="SINGLE_TO_RAID4"				
			elif [ "$Roption" == "5" ]; then
				OPTION_TYPE="SINGLE_TO_RAID5"
			elif [ "$Roption" == "6" ]; then
				OPTION_TYPE="SINGLE_TO_RAID6"
			elif [ "$Roption" == "10" ]; then
				OPTION_TYPE="SINGLE_TO_RAID10"
			else
				printerror "Option not available"
				exit 1
			fi			
			argw=${@:${OPTIND}:1}
			N=0
			while [ "${argw:0:1}" != "-" ]
			do
				DISK[${N}]="/dev/$(echo ${@:${OPTIND}:1} | sed 's/\/dev\///g')"
				OPTIND=$((OPTIND+1))
				argw=${@:${OPTIND}:1}
				N=$((N+1))
			done					
			;;
	  	e)	OPTION_TYPE="ERASE"
	  		if [ "${OPTARG:0:1}" != "-" ]; then
				DISK[1]=/dev/$(echo ${OPTARG} | sed 's/\/dev\///g')
				break
			else
				printerror "-e option needs an argument!"
				exit 1
			fi
			;;
	  	d)	OPTION_TYPE="LIST_MODE"
			break
			;;
		l)	if [ "${OPTARG:0:1}" != "-" ]; then
				RAID_EXT="$OPTARG"
			else
				printerror "-l option needs an argument!"
				exit 1
			fi
			;;
		b)	BOOTP_MODE=1
			if [ "${OPTARG:0:1}" != "-" ]; then	# if next argument is not another -option, get the device names
				bp_arg1="$OPTARG"
				parse_bp_arg ${bp_arg1}
				pbpres=$?
				if [ $pbpres -eq 2 ]; then
					BOOTP_MODE=-1	# force no bootp_mode
				elif [ $pbpres -eq 1 ]; then
					printerror "Error: -b option ${bp_arg1} not allowed!"
					exit 1
				fi
				if ! (echo ${@:${OPTIND}:1} | grep -q ^"-"); then
					bp_arg2=${@:${OPTIND}:1}
					if ! parse_bp_arg ${bp_arg2} ; then
						printerror "Error: -b option ${bp_arg2} not allowed!"
						exit 1
					fi
					shift
				fi
			else
				OPTIND=$((OPTIND-1))	# it was expecting an argument that was empty
			fi
			;;
		t)	TEST_MODE=1
			;;
		s)	SWAPRAIDER_MODE=1
			;;
		h)	OPTION_TYPE="HELP_MODE"
			break
			;;
		V)	OPTION_TYPE="VERSION_MODE"
			break
			;;
		\?)
			# to deal with --long-arguments
			for b in ${@:$OPTIND}; do
				break; done
			if [ "$b" == "${long_options[0]}" ]; then		#"--version"
				OPTION_TYPE="VERSION_MODE"
				shift $OPTIND
				OPTIND=1
				break
			elif [ "$b" == "${long_options[16]}" ]; then		#"--version-number"
				OPTION_TYPE="VERSION_NUMBER"
				shift $OPTIND
				OPTIND=1
				break
			elif [ "$b" == "${long_options[17]}" ]; then		#"--revision-number
				OPTION_TYPE="REVISION_NUMBER"
				shift $OPTIND
				OPTIND=1
				break			
			elif [ "$b" == "${long_options[1]}" ]; then		#"--disklist"
				OPTION_TYPE="LIST_MODE"
				shift $OPTIND
				OPTIND=1
				break
			elif [ "$b" == "${long_options[12]}" ]; then	# --run
				OPTION_TYPE="RUN_MODE"
				shift $OPTIND
				OPTIND=1
				break						
			elif [ "$b" == "${long_options[11]}" ]; then	#--lvm-suffix
				argl=${@:${OPTIND}+1:1}
				if [ "${argb:0:1}" != "-" ]; then
					RAID_EXT="${@:${OPTIND}+1:1}"
					shift $((OPTIND+1))
					OPTIND=1
				else
					printerror "--lvm-suffix needs an argument!"
					exit 1
				fi
			elif [ "$b" == "${long_options[14]}" ]; then	#"--boot"
				BOOTP_MODE=1
				argb=${@:${OPTIND}+1:1}
				T=0
				if [ "${argb:0:1}" != "-" ]; then	# if next argument is not another -option, get the device names
					T=$(( T+1 ))
					parse_bp_arg ${argb}
					pbpres=$?
					if [ $pbpres -eq 2 ]; then
						BOOTP_MODE=-1	# force no bootp_mode
					elif [ $pbpres -eq 1 ]; then
						printerror "-b option ${bp_arg1} not allowed!"
						exit 1
					fi
					argb=${@:${OPTIND}+2:1}
					if ! (echo ${argb} | grep -q ^"-"); then
						T=$(( T+1 ))
						if ! parse_bp_arg ${argb} ; then
							printerror "-b option ${bp_arg2} not allowed!"
							exit 1
						fi
					fi
					shift $(( OPTIND+T ))
					OPTIND=1
				else
					shift 2
					OPTIND=1
				fi				

			elif [ "$b" == "${long_options[2]}" ]; then		#"--swapraider"
				SWAPRAIDER_MODE=1
				shift $OPTIND
				OPTIND=1
			elif [ "$b" == "${long_options[18]}" ]; then	#"--no-swapraider"
				NO_SWAPRAIDER=1
				shift $OPTIND
				OPTIND=1
			elif [ "$b" == "${long_options[15]}" ]; then	#"--test"
				TEST_MODE=1
				shift $OPTIND
				OPTIND=1				
			elif [ "$b" == "${long_options[3]}" ]; then		#"--help"
				OPTION_TYPE="HELP_MODE"
				shift $OPTIND
				OPTIND=1
				break	
			elif [ "$b" == "${long_options[13]}" ]; then	#--debug
				DEBUG_MODE=1
				shift $OPTIND
				OPTIND=1
				break
			
			elif [  "${b:0:16}" == "--single-to-raid" ] ; then	# --single-to-raid1/4/5/6/10
				OPTION_TYPE="SINGLE_TO_RAID${b:16}"
				argw=${@:${OPTIND}+1:1}
				N=0
				while [ "${argw:0:1}" != "-" ]
				do
					DISK[${N}]="/dev/$(echo ${@:${OPTIND}+1:1} | sed 's/\/dev\///g')"
					OPTIND=$((OPTIND+1))
					argw=${@:${OPTIND}+1:1}
					N=$((N+1))
				done
				shift $(( N+2 ))
				OPTIND=1			

			elif [ "$b" == "${long_options[10]}" ]; then	#"--erase"
				arge=${@:${OPTIND}+1:1}
				if [ "${arge:0:1}" == "-" ]; then
					printerror "--erase option needs an argument!"
					exit 1
				fi
				OPTION_TYPE="ERASE"
				DISK[1]=/dev/$(echo ${@:${OPTIND}+1:1} | sed 's/\/dev\///g')
				if [ -z "${DISK[1]}" ]; then
					printerror "disk not found!"
					exit
				fi
				shift 2
				OPTIND=1			
			else
				printerror "Option not found!"
				exit 1
			fi
			;;		
	esac	
done

if [ -z "$OPTION_TYPE" ]; then
	if ! [ -z $1 ]; then
		printerror "Arguments missing"
		exit 1
	fi
fi

# Check if all commands exist
commands_not_found=$(check_commands)
if ! [ -z "$commands_not_found" ]; then
	check_root		# in some distros, system commands are only searchable by root
	echo "Aborted! Command(s) not found:"
	for i in $commands_not_found; do
		echoing "  $i"
	done
	echoing "Install them before running $PROGRAM_NAME"
	exit 1
fi

get_utils_versions
error_utils=""
p_version=2.6.18
if ! (check_utils_versions $KERNEL_VERSION ${p_version}); then
	error_utils="Kernel-$(uname -r) not accepted. You need a version greater or equal then ${p_version}\n"
fi
p_version=3.0.0
if ! (check_utils_versions $BASH_VERSION ${p_version}); then
	error_utils="${error_utils}Bash-${BASH_VERSION} not accepted. You need a version greater or equal then ${p_version}\n"
fi
p_version=2.6.0
if ! (check_utils_versions $MDADM_VERSION ${p_version}); then
	error_utils="${error_utils}Mdadm-${MDADM_VERSION} not accepted. You need a version greater or equal then ${p_version}\n"
fi

if [ -n "$error_utils" ]; then
	echo -e $error_utils
	exit 1
fi

if ! (check_latest_raider) ; then
	nvraider=$(cat $R_LIB/new_raider_version )
	echo "******************************************"
	echo "There is a newer version: $nvraider"
	echo "It is advisable to upgrade raider!"
	echo "******************************************"
fi

if [ "$OPTION_TYPE" == "HELP_MODE" ]; then
	description				# need not create temp files
elif [ "$OPTION_TYPE" == "LIST_MODE" ]; then
	listdevices				# need /tmp files
elif [ "$OPTION_TYPE" == "VERSION_MODE" ]; then
	version_info				# need not create temp files
elif [ "$OPTION_TYPE" == "VERSION_NUMBER" ]; then
	version_number
elif [ "$OPTION_TYPE" == "REVISION_NUMBER" ]; then
	revision_number
elif [ "$OPTION_TYPE" == "SINGLE_TO_RAID1" ]; then
	single_to_raid1
elif [ "$OPTION_TYPE" == "SINGLE_TO_RAID4" ]; then
	single_to_raid4
elif [ "$OPTION_TYPE" == "SINGLE_TO_RAID5" ];then
	single_to_raid5
elif [ "$OPTION_TYPE" == "SINGLE_TO_RAID6" ]; then
	single_to_raid6
elif [ "$OPTION_TYPE" == "SINGLE_TO_RAID10" ];then
	single_to_raid10
elif [ "$OPTION_TYPE" == "ERASE" ]; then
	clear_disk ${DISK[1]}			# need not create temp files
elif [ "$OPTION_TYPE" == "RUN_MODE" ]; then
	raider_run
else
	step_scan
	if [ $STEP -eq 2 ]; then
		echoing "Warning:"
		echoing "Run command \"raider --run\" to build raid array in the new disk (BuildRaid phase)"		
	elif [ $STEP -eq 0 ]; then
		echoing "Warning:"
		echoing "Oops!! You have completed BuildRaid phase."
		echoing "Change disks first, before running \"raider --run\""
	elif [ $STEP -eq 3 ]; then
		echoing "Warning:"
		echoing "Run command \"raider --run\" to start RaidSync phase, and complete the process"
		echoing "The old disk would be added to the new raid array"
	else	# if 1 or 99(no stepfile)
		description
	fi	
fi



