#!/usr/bin/sh
n=1
CONFIG_FILE=/opt/OceanProtect/conf/file_mountIp.txt
STORAGE_IP_FILE=/opt/OceanProtect/conf/storageIpList.txt
REP_ASSOCIATION_FILE=/opt/OceanProtect/conf/ReplicationRelation.txt
FORMAT="Format: <Storage Server> <LSU name> <FS name> <Logic Port IPs>"
STORAGE_IP_FORMAT="Format: <Storage Server> <Storage IPs>"
REP_ASSOCIATION_FORMAT="Format: <Source Storage Server> <Source Filesystem Name> <Target Filesystem Name> <Target Storage Server>"
function check_kernel(){
    if [ -f "/etc/redhat-release" ];then
        KERNEL=`uname -r`
        if [ "${KERNEL}" = "3.10.0-957.el7.x86_64" ];then
            printf "\\033[1;31mCurrent kernel version is 3.10.0-957.el7.x86_64, Please upgrade to 3.10.0-957.5.1.el7 or above. You can do this after plugin installation. If you don't upgrade kernel, when controller fault and back to normal, you may cannot mount to NFS filesystem, the backup or restore job will fail. \\033[0m \n"
            read -p "Do you want to continue (y/n)?" choice
            case "$choice" in
                y|Y ) return 0;;
                n|N|* ) return 1;;
            esac
       fi
    fi
}

function init(){
	if [ ! -f "${CONFIG_FILE}" ]; then
		echo "" >  ${CONFIG_FILE}
	fi
}

function checkIsItemRecord() {
    storageserver=$1
    filesystem=$2

    cnt=`grep "$storageserver" ${CONFIG_FILE} | wc -l`
    if [ $cnt -eq 0 ]; then
        return 0
    fi

    IFS=$'\n'
    for i in `grep "$storageserver" ${CONFIG_FILE}`
    do
        eval "arr=($i)"
        if [ "$storageserver" = "${arr[0]}" ] && [ "$filesystem" = "${arr[2]}" ]; then
            return 1
        fi
    done
    return 0
}

function insert() {
	while true
	do
		read -p "Please enter Storage Server Name: " storageserver
		if [ ! -z "$storageserver" ]; then
			break;
		fi
	done
	while true
	do
		read -p "Please enter LSU(Logic Storage Unit) name: " lsu
		if [ ! -z "$lsu" ]; then
			break;
		fi
	done
	while true
	do
		read -p "Please enter file system name: " filesystem
		if [ ! -z "$filesystem" ]; then
			break;
		fi
	done

    checkIsItemRecord $storageserver $filesystem
    if [ $? -ne 0 ]; then
        echo "The LSU has been exist."
        return
    fi

    read -p "Please enter useful IPs in a line divide by white space: " ips
    eval "arr=($ips)"
	iplist=""
	uname=`uname`
    for ip in "${arr[@]}"; do
		if [ "${uname}" == "Linux" ]; then
			ping_result=`timeout 0.2 ping -c 1  ${ip} &> /dev/null && echo 0 || echo 1`
		elif [ "${uname}" == "SunOS" ]; then
		    ping ${ip} 
		    ping_result=`echo $?`
		else
		    ping ${ip} 
		    ping_result=`echo $?`
		fi
        if [ "${ping_result}" -eq "0" ]; then
            printf "\\033[0;32mIp address [${ip}] is valid \\033[0m \n"
			iplist="$iplist $ip"
        else
            printf "\\033[1;31mError : Ip address [${ip}] is not reachable or is invalid. \\033[0m \n"
        fi
    done
    if [ ! -z "$iplist" ]; then
        inputLine="$storageserver $lsu $filesystem $iplist"
        echo $inputLine >> ${CONFIG_FILE}
        cat ${CONFIG_FILE} | sort | uniq > ${CONFIG_FILE}.bak
        cat ${CONFIG_FILE}.bak > ${CONFIG_FILE}
    fi
}

function modify(){
	printf "\\033[1;31mModify will delete original then add new links. \\033[0m \n"
	while true
	do
		read -p "Please enter original links($FORMAT): " original
		if [ ! -z "$original" ]; then
			cnt=`grep "$original" ${CONFIG_FILE} | wc -l`
			if [ "$cnt" -gt "0" ]; then
				break;
			else
				echo [$original] not exist, Please input again.
			fi
		fi
	done
	deleteLsu "$original"
	insert
}

function list(){
	printf "\\033[1;31mCurrent file system links: \\033[0m \n"
	echo $FORMAT
	if [ -f "${CONFIG_FILE}" ]; then
		cat ${CONFIG_FILE} | sort 
	fi	
}

function search(){
	read -p "Please enter key words: " keywords
	if [ ! -z "$keywords" ]; then
		printf "\\033[1;31mMatched links: \\033[0m \n"
		awk "/$keywords/" ${CONFIG_FILE} 
	fi
}

function deleteLsu() {
	sed "/^$1/d" ${CONFIG_FILE} > ${CONFIG_FILE}.bak;
	mv ${CONFIG_FILE}.bak ${CONFIG_FILE}
}
function delete(){
	read -p "Please enter links($FORMAT): " delete
	if [ ! -z "$delete" ]; then
		cnt=`grep "$delete" ${CONFIG_FILE} | wc -l`
		if [ "$cnt" -gt "0" ]; then
            read -p "Delete LSU will remove mount points, Do you want to continue (y/n)?" choice
			if [ ! -z "${choice}" ] && [ "${choice}" == "Y" ] || [ "${choice}" == "y" ]; then
				eval "arr=($delete)"
				if [ ! -z "${arr[0]}" ] && [ ! -z "${arr[1]}" ] && [ ! -z "${arr[2]}" ]; then
					deleteLsu "$delete"
					# single link
					removeMoontPoints  "/OceanProtect/${arr[0]}/${arr[2]} "
					# Multiple link 
					removeMoontPoints  "/OceanProtect/${arr[0]}/${arr[2]}/"
				fi
			fi
		else
			echo [$delete] not exist, Skip delete.
		fi	
	fi
}

function removeMoontPoints() {
    echo Will remove mount points: $1
    uname=`uname`
    if [ "${uname}" == "Linux" ]; then
        mount | grep "on $1" | awk '{position=$3; print position}' | xargs umount -f  >/dev/null 2>&1
    elif [ "${uname}" == "SunOS" ]; then
        clearMountPoints=clearMountPoints.list
        mount | grep "$1" | awk '{position=$1; print position}' > ${clearMountPoints}
        if [ -f "${clearMountPoints}" ]; then
            while IFS= read -r line
            do
                umount -f $line
            done < "${clearMountPoints}"
            rm -rf ${clearMountPoints}
        fi
    else
        echo "Skip mount points: $1 for $uname"
    fi
}
function apply(){
	read -p "Please enter Storage Server Address: " server
	read -p "Please enter User Name: " username
	read -s -p "Please enter Password: " password
	echo ""
	if [ ! -z "$server" ] && [ ! -z "$username" ] && [ ! -z "$password" ]; then
		echo $server $username $password
		printf "\\033[0;32mCheck Server Connection \\033[0m \n"
		printf "\\033[0;32mMount File system \\033[0m \n"
		mkdir -p /OceanProtect/${server}
		if [ -f "${CONFIG_FILE}" ]; then
			while IFS= read -r line
			do
				eval "arr=($line)"
				if [ ! -z "${arr[0]}" ] && [ ! -z "${arr[1]}" ] && [ ! -z "${arr[2]}" ]; then
					echo "mount -t nfs ${arr[2]}:/${arr[1]} /OceanProtect/${server}/${arr[1]}"
				fi
			done < "${CONFIG_FILE}"	
		fi
	fi
}

function add_filesystem_and_storage() {
	while [ "$n" > 0 ];
	do
		init
		echo "=========================================="
		printf "\\033[0;32mFileSystem And StorageServer Management \\033[0m \n"
		echo "=========================================="
		echo "1-Add LSU"
		echo "2-List LSU"
		echo "3-Delete LSU"
		echo "4-Search LSU"
		echo "5-Add Storage Server"
		echo "6-List Storage Server"
		echo "7-Delete Storage Server"
		echo "8-Add Target AIR Replication Association"
		echo "9-List Target AIR Replication Association"
		echo "10-Delete Target AIR Replication Association"
		echo "0-Exit"
		echo "=========================================="
		read -p "Please Select: " option
		case "$option" in
		1) insert ;;
		2) list ;;
		3) delete ;;
		4) search ;;
		5) insert_storage_server ;;
		6) list_storage_server ;;
		7) delete_storage_server ;;
		8) insert_replication_association ;;
		9) list_replication_association ;;
		10) delete_replication_association ;;
		0) exit ;;
		esac
	done
}


function insert_storage_server() {
	while true
	do
		read -p "Please enter Storage Server Name: " storageserver
		if [ ! -z "$storageserver" ]; then
			break;
		fi
	done
    read -p "Please enter useful server IPs in a line divide by white space: " ips
    eval "arr=($ips)"
	iplist=""
	uname=`uname`
    for ip in "${arr[@]}"; do
		if [ "${uname}" == "Linux" ]; then
			ping_result=`timeout 0.2 ping -c 1  ${ip} &> /dev/null && echo 0 || echo 1`
		elif [ "${uname}" == "SunOS" ]; then
		    ping ${ip} 
		    ping_result=`echo $?`
		else
		    ping ${ip} 
		    ping_result=`echo $?`
		fi
        if [ "${ping_result}" -eq "0" ]; then
            printf "\\033[0;32mIp address [${ip}] is valid \\033[0m \n"
			iplist="$iplist $ip"
        else
            printf "\\033[1;31mError : Ip address [${ip}] is not reachable or is invalid. \\033[0m \n"
        fi
    done
    if [ ! -z "$iplist" ]; then
        inputLine="$storageserver $lsu $filesystem $iplist"
        echo $inputLine >> ${STORAGE_IP_FILE}
        cat ${STORAGE_IP_FILE} | sort | uniq > ${STORAGE_IP_FILE}.bak
        cat ${STORAGE_IP_FILE}.bak > ${STORAGE_IP_FILE}
    fi
}

function list_storage_server(){
	printf "\\033[1;31mCurrent storage server info: \\033[0m \n"
	echo $STORAGE_IP_FORMAT
	if [ -f "${STORAGE_IP_FILE}" ]; then
		cat ${STORAGE_IP_FILE} | sort 
	fi	
}
function deleteServerInfo() {
	sed "/^$1/d" ${STORAGE_IP_FILE} > ${STORAGE_IP_FILE}.bak;
	mv ${STORAGE_IP_FILE}.bak ${STORAGE_IP_FILE}
}

function delete_storage_server(){
	read -p "Please enter links($STORAGE_IP_FORMAT): " delete
	if [ ! -z "$delete" ]; then
		cnt=`grep "$delete" ${STORAGE_IP_FILE} | wc -l`
		if [ "$cnt" -gt "0" ]; then
            read -p "Delete Server info can't recover, Do you want to continue (y/n)?" choice
			if [ ! -z "${choice}" ] && [ "${choice}" == "Y" ] || [ "${choice}" == "y" ]; then
				deleteServerInfo "$delete"
			fi
		else
			echo [$delete] not exist, Skip delete.
		fi	
	fi
}

function insert_replication_association() {
	while true
	do
		read -p "Please enter Source Storage Server Name: " storageserver
		if [ ! -z "$storageserver" ]; then
			break;
		fi
	done
	while true
	do
		read -p "Please enter Source file system name: " srcfilesystem
		if [ ! -z "$srcfilesystem" ]; then
			break;
		fi
	done
	while true
	do
		read -p "Please enter Target file system name: " targetfilesystem
		if [ ! -z "$targetfilesystem" ]; then
			break;
		fi
	done
	while true
	do
		read -p "Please enter Target Storage Server Name: " targetstorageserver
		if [ ! -z "$targetstorageserver" ]; then
			break;
		fi
	done

	inputLine="$storageserver $srcfilesystem $targetfilesystem $targetstorageserver"
	echo $inputLine >> ${REP_ASSOCIATION_FILE}
	cat ${REP_ASSOCIATION_FILE} | sort | uniq > ${REP_ASSOCIATION_FILE}.bak
	cat ${REP_ASSOCIATION_FILE}.bak > ${REP_ASSOCIATION_FILE}
}

function list_replication_association(){
	printf "\\033[1;31mCurrent storage server info: \\033[0m \n"
	echo $REP_ASSOCIATION_FORMAT
	if [ -f "${REP_ASSOCIATION_FILE}" ]; then
		cat ${REP_ASSOCIATION_FILE} | sort 
	fi	
}

function delete_replication_association() {
	read -p "Please enter links($REP_ASSOCIATION_FORMAT): " delete
	if [ ! -z "$delete" ]; then
		cnt=`grep "$delete" ${REP_ASSOCIATION_FILE} | wc -l`
		if [ "$cnt" -gt "0" ]; then
            read -p "Delete Replication info can't recover, Do you want to continue (y/n)?" choice
			if [ ! -z "${choice}" ] && [ "${choice}" == "Y" ] || [ "${choice}" == "y" ]; then
				sed "/^$delete/d" ${REP_ASSOCIATION_FILE} > ${REP_ASSOCIATION_FILE}.bak;
				mv ${REP_ASSOCIATION_FILE}.bak ${REP_ASSOCIATION_FILE}
				echo "delete $delete success"
			fi
		else
			echo [$delete] not exist, Skip delete.
		fi	
	fi
}