#!/bin/bash
#
#       Copyright (C) MOXA Inc. All rights reserved.
#       Copyright (C) 2015       Andy CY Chen <AndyCY.Chen@moxa.com>
#
#       This software is distributed under the terms of the
#       MOXA License.  See the file COPYING-MOXA for details.
#
#       Smart Recovery
#               backup, recovery automatically. This version support DA-682A seris 
#

tmp_master=""
tmp_slave=""
tmp_sync_status=""
tmp_last_sync_date=""
# to indicate whether finish select master and slave #
tmp_flag=0


# if .srcfg is not exist -> create one with default setting #
if ! [ -e /etc/smart_recovery/.srcfg ]; then
        echo "MASTER_STORAGE=/dev/sda" > /etc/smart_recovery/.srcfg
        echo "SLAVE_STORAGE=/dev/sdb" >> /etc/smart_recovery/.srcfg
        echo "AUTO_SYNC=\"OFF\"" >> /etc/smart_recovery/.srcfg
        echo "LAST_SYNC_DATE=\"\"" >> /etc/smart_recovery/.srcfg
fi

# when automatically backup or recovery is on, set rc.local #
# $1 = 0, remove script from rc.local
# $1 = 1, add script in rc.local
call_modify_rclocal() 
{
	local opt=$1
	# remove #
	if [ 0 == $opt ]; then
		# check whether has script in the rc.local #
		ret=`cat /etc/rc.local | grep smart_recovery_rc.sh`	
		# there is no script to remove #
		if [ "x" == x$ret ]; then
			return 0
		fi
		# check auto backup and recovery, should both be OFF, then remove #
		source /etc/smart_recovery/.srcfg
		if [ "XON" == X$AUTO_SYNC ]; then
			return 0
		fi
		local mode=`/sbin/sr_wr_cmos 0 E9 | awk -F "=" '{printf $2}'`
		if [ "X2" == X$mode ]; then
			return 0
		fi
		# remove the script line #
		sed -i.bak '/smart_recovery_rc.sh/d' /etc/rc.local
	# add #
	else
		# check whether has script line in rc.local #
		ret=`cat /etc/rc.local | grep smart_recovery_rc.sh`
		# there is already have script line -> exit #
		if ! [ x == x$ret ]; then
			return 0
		fi
		# add the sciprt line #
		#sed -i 's/exit 0/\/sbin\/smart_recovery_rc.sh\n&/' /etc/rc.local
		sed -i '$ i /sbin/smart_recovery_rc.sh' /etc/rc.local 
	fi
		
}

call_get_list_storage()
{
	fdisk -l | grep "Disk /dev" | awk '{print $2}'
	count=1

        for device in `fdisk -l | grep "Disk /dev" | awk '{print $2}'`; do
	        device_array[$count]="$device"
                count=$(( $count + 1 ))
        done



}

call_auto_sync(){

	source /etc/smart_recovery/.srcfg

	local SYNC_1="OFF"
	local SYNC_2="ON"
	
	if [ "$AUTO_SYNC" == "ON" ] ; then
		SYNC_1="ON"
		SYNC_2="OFF"
	else
		SYNC_1="OFF"
		SYNC_2="ON"
	fi

	SYNC_STATUS_BAK=$(whiptail --title "Automatic Synchronization" --radiolist \
		"Do you want to synchronize automatically from master to slave storage every boot time?" 20 90 6 \
		"ON" "" "$SYNC_1" \
		"OFF" "" "$SYNC_2" 3>&1 1>&2 2>&3)
	

	if [ "$?" = "0" ]; then
		sed -i "s/.*AUTO_SYNC=.*/AUTO_SYNC=\"$SYNC_STATUS_BAK\"/g" /etc/smart_recovery/.srcfg
		
	fi

	if [ x$SYNC_STATUS_BAK == "xON" ]; then
		# add script to rc.local #
		call_modify_rclocal 1 
		whiptail --title "Automatic Synchronization" --msgbox "\n\n		Automatic Synchronization is on.\n" 10 50
	else
		# remove script from rc.local #
		call_modify_rclocal 0
		whiptail --title "Automatic Synchronization" --msgbox "\n\n		Automatic Synchronization is off.\n" 10 50
	fi
}

call_auto_recovery() {
	# get mode from cmos #
	local mode=`/sbin/sr_wr_cmos 0 E9 | awk -F "=" '{printf $2}'`
	# just init #
	local REC_1="ON"
	local REC_2="OFF"

	# 2 is auto mode #		
	if [ "x2" == x$mode ]; then
		REC_1="ON"
		REC_2="OFF"
	else
		REC_1="OFF"
		REC_2="ON"
	fi

	REC_STATUS_BAK=$(whiptail --title "Automatic Recovery" --radiolist \
                "Do you want to recovery automatically from slave to master storage when boot fail?" 20 90 6 \
                "ON" "" "$REC_1" \
                "OFF" "" "$REC_2" 3>&1 1>&2 2>&3)

	user_choise=$?

	if [ $user_choise = 0 ]; then
	if [ x$REC_STATUS_BAK == "xON" ]; then
		# change the mode to auto mode #
		/sbin/sr_wr_cmos 1 E9 2
		# enable boot fail timeout #
		/sbin/sr_wr_cmos 1 ED 1
		# update rc.local #
		call_modify_rclocal 1

		source /sbin/smart_recovery_func.sh

		# sync slave's rc.local #
		mkdir -p /tmp/p2
		num_1="1"		
		umount_target $SLAVE_STORAGE$num_1
		mount $SLAVE_STORAGE$num_1 /tmp/p2
		
		rsync --delete -aqP /etc/rc.local /tmp/p2/etc/rc.local 
	
		# sync slave's /etc/smart_recovery/.srcfg #
		rsync --delete -aqP /etc/smart_recovery/.srcfg /tmp/p2/etc/smart_recovery/.srcfg

		umount_target /tmp/p2

		whiptail --title "Automatic Recovery" --msgbox "\n\n             Automatic Recovery is on.\n" 10 50
		call_options
	else
		# change the mode to plug-in mode #
		/sbin/sr_wr_cmos 1 E9 1
		# disable boot faile timeout #
		/sbin/sr_wr_cmos 1 ED 0

		call_modify_rclocal 0
		whiptail --title "Automatic Recovery" --msgbox "\n\n             Automatic Recovery is off.\n" 10 50
	fi
	fi
}


call_manually_recovery() {

	source /etc/smart_recovery/.srcfg

        if (whiptail --title "Reocvery" --yes-button "Recovery" --no-button "Cancel"  --yesno "Recovery immediately from slave to master\n\nMaster: $MASTER_STORAGE \n\nSalve: $SLAVE_STORAGE" 15 50) then
		/sbin/sr_wr_cmos 0 E9 3
		/sbin/sr_wr_cmos 3 B2 121

		if (whiptail --title "Reocvery" --yes-button "Reboot" --no-button "Cancel"  --yesno "!!!System needs to reboot for recovery!!!" 15 50) then	
			reboot
		else
			return 0
		fi
	else
		return 0
	fi

}


# Backup immediately #
call_backup() {

	# read config #
	source /etc/smart_recovery/.srcfg
	
        if (whiptail --title "Synchronization" --yes-button "Sync" --no-button "Cancel"  --yesno "Synchronize immediately\n\nMaster: $MASTER_STORAGE \n\nSalve: $SLAVE_STORAGE" 15 50) then
                #sync immediately
		source /sbin/smart_recovery_func.sh
		#echo "Synchronize from $MASTER_STORAGE to $SLAVE_STORAGE ... "
	
	        # check storage #
	        run_check_storage $MASTER_STORAGE $SLAVE_STORAGE
		ret="$?"
		# if check storage return code != 0 -> some error occur #
		if [ "x0" != x$ret ]; then
			# try to repair the repairable error (error code: 2, 3, 5) #
			if [ 2 == $ret ] || [ 3 == $ret ] || [ 5 == $ret ]; then
				# try to repair with DD_MDR, FDISK and MKFS
				# call_repair
				clone_storage_config
	
				# check storage again #
				run_check_storage $MASTER_STORAGE $SLAVE_STORAGE
				ret2=$?
				if [ "x0" != x$ret2 ]; then # the error repair failed #
					whiptail --title "Backup" --msgbox "\n\n	Storage error code: $ret2" 10 40
					return 0 
				fi
			else # the error can not be repaired#
				whiptail --title "Backup" --msgbox "\n\n        Storage error code: $ret" 10 40		
				return 0	
			fi
	       	fi

		# rsync each partition #
	
		# get partition number of master #
 
		num_1="1"
	        local local_par="$MASTER_STORAGE$num_1"
	        local target_par="$SLAVE_STORAGE$num_1"
	        # the target directory or file #
	        local target_df="$3"
		local count=0		
		local progress_count=0
		local progress_interval=0

        	# umount to avoid busy #
	        if [ x"" != x"`df | grep /tmp/p1`" ]; then
                	umount -f /tmp/p1 > /dev/null
        	fi

	        if [ x"" != x"`df | grep /tmp/p2`" ]; then
        	        umount -f /tmp/p2 > /dev/null
	        fi
	
	        # mount partitions to /tmp/p1 and p2 respecttively #
        	mount $local_par /tmp/p1 > /dev/null
	        mount $target_par /tmp/p2 > /dev/null

		# get file list #
		for f in `ls /tmp/p1`; do
			file_list[$count]="$f"
			count=$((count+1))	
		done 

		# calc progress_interval, if count >= 100, progress_interval would be 1 since without float here #	
		if [ $count -ge 100 ]; then
			progress_interval=1
		else
			progress_interval=$((100/count))	
		fi

		{
			for f in "${file_list[@]}"; do
				rsync --delete -aqP /tmp/p1/$f /tmp/p2 &>/dev/null
				progress_count=$((progress_count+progress_interval))
				echo $progress_count 
			done
		} | whiptail --gauge "The system is backup. Please wait a few minutes." 10 70 0

		# umount the partitions #
		umount -f /tmp/p1 &>/dev/null
		umount -f /tmp/p2 &>/dev/null

		### end of rsync each partition #

		# check master and slave label, if any wrong -> set it ! #
		run_check_label $local_par $target_par	

		# put a fat in last partition #
		put_fat 		
	
		# record the update date #
	        echo "MASTER_STORAGE=$MASTER_STORAGE" > /etc/smart_recovery/.srcfg
	        echo "SLAVE_STORAGE=$SLAVE_STORAGE" >> /etc/smart_recovery/.srcfg
	        echo "AUTO_SYNC=$AUTO_SYNC" >> /etc/smart_recovery/.srcfg
	        echo "LAST_SYNC_DATE=\"`date`\"" >> /etc/smart_recovery/.srcfg

		whiptail --title "Backup" --msgbox "\n\n	Backup is success!" 10 40
                
        else
                #cancel
                return 0
        fi
}

# to set master and slave storage
call_set_master_storage() {

	count=1
# Get device number # 
	#num_device=`df | awk '{print $1}' |grep -vE 'tmpfs|rootfs|udev|Filesystem' | wc -l`
	num_device="`fdisk -l | grep Disk | wc -l`"
	num_device=$((num_device/2))

# only one storage case #

#########################

	local LIST=()
	local device_array=()
#	for device in `df | awk '{print $1}' |grep -vE 'tmpfs|rootfs|udev|Filesystem'`; do
	for device in `fdisk -l | grep "Disk /dev" | awk '{print $2}'`; do
		# remove the last char, ex: "/dev/sda:" #
		device="${device%?}"
		device_array[$count]="$device"
		#ui_str="$ui_str\"$count\" \"$device\" "
		#LIST="$LIST $count $device"			
		LIST+=($count "$device")
		count=$(( $count + 1 ))
	done


	select_master=$(whiptail --title "Select Master Storage" --menu "Choose the MASTER storage" --ok-button Select 15 60 $num_device "${LIST[@]}" 3>&2 2>&1 1>&3)

	#eval $ui_str

	if [ $? = 0 ]; then
		tmp_master=${device_array[$select_master]}		
		call_set_slave_storage
	else
		return 0
	fi
}

# to set master and slave storage
call_set_slave_storage() {

        count=1
# Get device number #
        num_device="`fdisk -l | grep Disk | wc -l`"
        num_device=$((num_device/2))

# only one storage case #

#########################
	local device_array=()
        local LIST=()

#        for device in `df | awk '{print $1}' |grep -vE 'tmpfs|rootfs|udev|Filesystem'`; do
	 for device in `fdisk -l | grep "Disk /dev" | awk '{print $2}'`; do
		device="${device%?}"
                device_array[$count]="$device"
                #ui_str="$ui_str\"$count\" \"$device\" "
                #LIST="$LIST $count $device"
                LIST+=($count "$device")
                count=$(( $count + 1 ))
        done

        select_slave=$(whiptail --title "Select Slave Storage" --menu "Choose the SLAVE storage" --ok-button Select 15 60 $num_device "${LIST[@]}" 3>&2 2>&1 1>&3)

        #eval $ui_str

        if [ $? = 0 ]; then
                tmp_slave=${device_array[$select_slave]}
		tmp_flag=1
	else
		return 0
        fi
}



# comfirm page of select master/slave #
call_comfirm_select_ms() {
	if (whiptail --title "Comfirm Master/Salve Selection" --yes-button "Save" --no-button "Cancel"  --yesno "Master: $tmp_master \nSalve: $tmp_slave" 10 60) then
		# write to config #
		call_update_ms_to_config

		# write to cmos #
		# master controller in hex #
 		master_controller=`udevadm info -q path -n $tmp_master | awk -F ":" '{printf $4}' | awk -F "/" '{printf $1}' | awk -F "." '{printf $1}'`
		# master function in hex #
	 	master_fun=`udevadm info -q path -n $tmp_master | awk -F ":" '{printf $4}' | awk -F "/" '{printf $1}' | awk -F "." '{printf $2}'`
		# convert to decimal #
		mc_10=$((16#$master_controller))
		mf_10=$((16#$master_fun))
		# mc should shift 3 bit  
		# because F0 is 5 bits for saving controller 
		# 3 bits for saving function
		mc_10=$(($mc_10 << 3))
		mcf_10=$(($mc_10+$mf_10)) 
		ret=`/sbin/sr_wr_cmos 1 F0 $mcf_10`

		# slave controller and function are same process as master #
		slave_controller=`udevadm info -q path -n $tmp_slave | awk -F ":" '{printf $4}' | awk -F "/" '{printf $1}' | awk -F "." '{printf $1}'`
		slave_fun=`udevadm info -q path -n $tmp_slave | awk -F ":" '{printf $4}' | awk -F "/" '{printf $1}' | awk -F "." '{printf $2}'`
		sc_10=$((16#$slave_controller))
		sf_10=$((16#$slave_fun))
		sc_10=$(($sc_10 << 3))
		scf_10=$(($sc_10 + $sf_10))
		ret=`/sbin/sr_wr_cmos 1 F2 $scf_10`
		
		# set port and partition number #
		source /sbin/smart_recovery_func.sh
		#ret=`/sbin/sr_wr_cmos 1 F1 0`
		set_port 0 $tmp_master
		#ret=`/sbin/sr_wr_cmos 1 F3 16`
		set_port 1 $tmp_slave	

		#  udevadm info -q path -n /dev/sda1
	else
		#cancel
		return 0
	fi	
}

call_update_ms_to_config() {
	# read original setting #
        MASTER_STORAGE=`cat /etc/smart_recovery/.srcfg | grep MASTER_STORAGE | awk -F "=" '{print $2}'`
        SLAVE_STORAGE=`cat /etc/smart_recovery/.srcfg | grep SLAVE_STORAGE | awk -F "=" '{print $2}'`
        SYNC_STATUS=`cat /etc/smart_recovery/.srcfg | grep AUTO_SYNC | awk -F "=" '{print $2}'`
	SYNC_DATE=`cat /etc/smart_recovery/.srcfg | grep LAST_SYNC_DATE | awk -F "=" '{printf $2}'`	
	# update master and slave #
	MASTER_STORAGE=$tmp_master
	SLAVE_STORAGE=$tmp_slave

	# write back to config file #
        echo "MASTER_STORAGE=$MASTER_STORAGE" > /etc/smart_recovery/.srcfg
        echo "SLAVE_STORAGE=$SLAVE_STORAGE" >> /etc/smart_recovery/.srcfg
        echo "AUTO_SYNC=$SYNC_STATUS" >> /etc/smart_recovery/.srcfg
	echo "LAST_SYNC_DATE=$SYNC_DATE" >> /etc/smart_recovery/.srcfg 	
}

call_read_ms_config() {
        # read original setting #
        tmp_master=`cat /etc/smart_recovery/.srcfg | grep MASTER_STORAGE | awk -F "=" '{print $2}'`
        tmp_slave=`cat /etc/smart_recovery/.srcfg | grep SLAVE_STORAGE | awk -F "=" '{print $2}'`
	tmp_sync_status=`cat /etc/smart_recovery/.srcfg | grep AUTO_SYNC | awk -F "=" '{printf $2}'`
	tmp_last_sync_date=`cat /etc/smart_recovery/.srcfg | grep LAST_SYNC_DATE | awk -F "=" '{printf $2}'`
}

call_show_setting_info(){

	# Get number of storage device #	
	num_device=`df | awk '{print $1}' |grep -vE 'tmpfs|rootfs|udev|Filesystem' | wc -l`	
	num_device=`fdisk -l | grep Disk | wc -l`
	num_device=$((num_device/2))

	# Get slave available, used and usage #

	# Get master and slave from config into tmp_master, tmp_slave and tmp_sync_status  #
	call_read_ms_config

	# check are master / slave exist ? #
	if ! [ -e "$tmp_master" ] || ! [ -e "$tmp_slave" ]; then
		whiptail --title "Device Not Found" --msgbox "Master / Slave storage are not found." 10 60		
		return 1
	fi

	# get total space of the storage #
	tmp_master_total=`fdisk -l | grep "Disk $tmp_master" | awk '{print $3}'`
	tmp_master_unit=`fdisk -l | grep "Disk $tmp_master" | awk '{print $4}'`

	tmp_slave_total=`fdisk -l | grep "Disk $tmp_slave" | awk '{print $3}'`
	tmp_slave_unit=`fdisk -l | grep "Disk $tmp_slave" | awk '{print $4}'`


	# remove the "," #
	tmp_master_unit=${tmp_master_unit%?}
	tmp_slave_unit=${tmp_slave_unit%?}



	#tmp_sync_status=`echo $tmp_sync_status | awk -F "\"" '{printf $2}'`
	#tmp_last_sync_date=`echo $tmp_last_sync_date | awk -F "\"" '{printf $2}'`

	whiptail --title "Information" --msgbox "Moxa Smart Recovery v1.0.0\n\n
Number of Device:$num_device\n\n\
Master Storage : $tmp_master\n\
Space : $tmp_master_total $tmp_master_unit\n
Slave Storage : $tmp_slave\n\
Space : $tmp_slave_total $tmp_slave_unit\n
Automatic Synchronization : $tmp_sync_status\n
Last Synchronization Time : $tmp_last_sync_date\n
" 20 80

}


call_recoverys() {

while [ 1 ]
do

	local read_opt=`sr_wr_cmos 0 E9 | awk -F "=" '{printf $2}'`
	local selected_1=""
	local selected_2=""
	local selected_3=""
	local selected_0=""

	case $read_opt in
		"3")
			selected_1="(Selected)"
			;;
		"2") 
			selected_2="(Selected)"
			;;

		"1")
			selected_3="(Selected)"
			;;
		"0")
			selected_0="(Selected)"
			;;
		*)
			;;
	esac

	recovery_opt=$(whiptail --title "Recovery Mode" --menu "Choose a recovery mode " 15 60 5 \
		"1" "Turn Off $selected_0" \
		"2" "Manual Recovery $selected_1" \
		"3" "Fully Automated Recovery $selected_2" \
		"4" "User-Initiated Recovery $selected_3"	3>&1 1>&2 2>&3)


	if [ $? == 0 ]; then


		case $recovery_opt in
			"1")
				/sbin/sr_wr_cmos 1 E9 0
				;;
			"2")
				call_manually_recovery
				;;
			"3")
				call_auto_recovery			
				;;
			"4")
				/sbin/sr_wr_cmos 1 E9 1
				/sbin/sr_wr_cmos 3 B2 121
				;;
			*)
				;;
		esac

	else
		return 0
	fi

done

}

call_options() {

while [ 1 ]
do

	# get watchdog timeout from watchdog #
	default_timeout=`/sbin/sr_wr_cmos 0 ED | awk -F "=" '{printf $2}'`		
	# get retry times from cmos #
	retry_times=`/sbin/sr_wr_cmos 0 EF | awk -F "=" '{printf $2}'`
	# get boot fail count #
	boot_fail_count=`/sbin/sr_wr_cmos 0 EE | awk -F "=" '{printf $2}'`

	source /etc/smart_recovery/.rectime
	
	# to check schedule options #
	if [ "xON" == x$r_opt ]; then
		local r_str="in $r_day day $r_hour hour"
	else
		local r_str="[Disable]"
	fi	

	cOPTION=$(whiptail --title "Options" --menu "Choose an option (enter) to set" 15 75 5 \
		"1" "Watchdog timeout for boot failure $default_timeout minutes" \
		"2" "Recovery retry attempts (max) $retry_times times" \
		"3" "Boot fail count $boot_fail_count times" \
		"4" "Sheduled recovery $r_str" 	3>&1 1>&2 2>&3)	

	if [ $? == 0 ]; then
		case $cOPTION in
		"1")
			wdt_timeout=$(whiptail --title "Set Wachdog Timeout" --inputbox "Timeout value for boot failure (0-255 minutes), 0 is disable" 10 60 3>&1 1>&2 2>&3)

			# if enter a value #
			if [ 0 == $? ]; then
				# disable watchdog for boot failure timeout #
					if [ "x0" == "x"$wdt_timeout ]; then
					# set timeout #
					ret=`/sbin/sr_wr_cmos 1 ED 0`
				else
					if [[ ( 255 -le $wdt_timeout ) || ( 0 -gt $wdt_timeout ) ]]; then
						# if timeout > 255, set to 255 #
						/sbin/sr_wr_cmos 1 ED 255
						wdt_timeout=255
					else
						/sbin/sr_wr_cmos 1 ED $wdt_timeout
					fi
				fi
			
				whiptail --title "Set Watchdog Timeout" --msgbox "\n\n		Watchdog timeout is set to $wdt_timeout.\n" 10 55
			fi
			;;
		"2")
			retry_times=$(whiptail --title "Set Recovery Retry" --inputbox "Retry attemps value (range 1-3)" 10 60 3>&1 1>&2 2>&3)

			# if enter a vlue #
			if [ 0 == $? ]; then
				if [[ ( 3 -le $retry_times ) || ( 0 -gt $retry_times ) ]]; then
					ret=`/sbin/sr_wr_cmos 1 EF 3`
					retry_times=3
				else
					ret=`/sbin/sr_wr_cmos 1 EF $retry_times`	
				fi
			fi	

			;;
		"3")	# range 1 ~ 5 #
			boot_fail_count=$(whiptail --title "Set Boot Failure Count" --inputbox "After the count of boot failure, the system will be recovery" 10 60 3>&1 1>&2 2>&3)
			                        # if enter a vlue #
                        if [ 0 == $? ]; then
                                if [[ ( 5 -le $boot_fail_count ) || ( 0 -ge $boot_fail_count ) ]]; then
                                        ret=`/sbin/sr_wr_cmos 1 EE 5`
                                        retry_times=5
                                else
                                        ret=`/sbin/sr_wr_cmos 1 EE $boot_fail_count`
                                fi
                        fi


			;;
		"4")
			# schedule recovery ON/OFF #
			        local SYNC_1="OFF"
			        local SYNC_2="ON"

		        if [ "$r_opt" == "ON" ] ; then
		                SYNC_1="ON"
		                SYNC_2="OFF"
		        else
		                SYNC_1="OFF"
		                SYNC_2="ON"
		        fi

		        SYNC_STATUS_BAK=$(whiptail --title "Schedule Recovery" --radiolist \
	                "Do you want to recovery automatically from slave to master storage in set time?" 20 90 6 \
	                "ON" "" "$SYNC_1" \
	                "OFF" "" "$SYNC_2" 3>&1 1>&2 2>&3)

		        if [ "$?" = "0" ]; then
		        	if [ x$SYNC_STATUS_BAK == "xON" ]; then
		                	# add script to rc.local #
			                # whiptail --title "Automatic Synchronization" --msgbox "\n\n             Automatic Synchronization is on.\n" 10 50
					local new_day=0
					local new_hour=0
		                        new_day=$(whiptail --title "Set Schedule Recovery days" --inputbox "After the DAYS, the system will be recovery automatically" 10 60 3>&1 1>&2 2>&3)
	        	                new_hour=$(whiptail --title "Set Schedule Recovery hours" --inputbox "After the HOURS, the system will be recovery automatically" 10 60 3>&1 1>&2 2>&3)

					if [ $new_day == 0 ] || [ $new_hour == 0 ]; then
						return 0
					fi
					sed -i "s/.*r_day=.*/r_day=\"$new_day\"/g" /etc/smart_recovery/.rectime
					sed -i "s/.*r_hour=.*/r_hour=\"$new_hour\"/g" /etc/smart_recovery/.rectime
				fi
		        
			        sed -i "s/.*r_opt=.*/r_opt=\"$SYNC_STATUS_BAK\"/g" /etc/smart_recovery/.rectime
			fi
				;;
		*)
			;;
		esac
	else 
		return 0	
	fi
done

}



# detect whethre is root #
 if id | grep root > /dev/null
 then
 :
 else
 echo "You must be root to run Moxa Smart Recovery."
 exit 1
 fi

while [ 1 ]
do

	 OPTION=$(whiptail --title "Moxa Smart Recovery" --menu "Choose your option" 15 60 7 \
		"1" "Backup"\
		"2" "Select Recovery Mode"\
		"3" "Automatic Synchronization" \
		"4" "Set Master and Slave Storage" \
		"5" "Options" \
		"6" "Show Setting Info"		3>&1 1>&2 2>&3)
 
	if [ $? = 0 ]; then
		case $OPTION in
		"3")
			call_auto_sync;
			;;
		"4")
			#cell_set_sync_storage;
			call_set_master_storage;
			if [ 1 == $tmp_flag ]; then
				call_comfirm_select_ms;
				tmp_flag=0
			fi
			;;
		"6")
			call_show_setting_info;
			;;
		"1")
			call_backup;
			;;
		"5")
			call_options;
			;;
		"4")
			call_auto_recovery;
			;;
		"2")
			call_recoverys;
			;;
		 *)
			call_error_massage;
			;;
		esac
	else
		#clear
    		exit;
	fi

done
