#!/usr/bin/bash

# ksvd-prepare-brick dev type(exact or like) number name from% to%
#                     1    2                   3     4     5    6
# ksvd-prepare-brick /dev/sdb exact 1 ksvd 0% 100%
# ksvd-prepare-brick /dev/sdb exact 2 ksvd2 50% 100%
# ksvd-prepare-brick md like 1 ksvd 0% 100%


DEPLOYGLUSTERLOG="/var/log/ksvd-deploy/ksvd-prepare-brick.log"

usage()
{
	cat <<EOT
Usage: ksvd-prepare-brick dev type(exact or like) number(which partition) name from% to%

examples:
       ksvd-prepare-brick /dev/sdb exact 1 ksvd 0% 100%
       ksvd-prepare-brick /dev/sdb exact 1 ksvd 0% 50%
       ksvd-prepare-brick /dev/sdb exact 2 ksvd2 50% 100%
       ksvd-prepare-brick md like 1 ksvd 0% 100%

EOT
}


get_brick_dev()
{
	#lsblk -f -n -l |sed "^$1"
	#grep "^md" test|sort |uniq|awk 'BEGIN {count=0}{if($4=="/") devroot=$1 else {devs[count]=$1;count=count+1}}'
	if [ "$1"x = "md"x ]; then
		eval $(lsblk -n -l -b -p|grep "md"|awk 'BEGIN {size=0;target="";}
					{if ($4 > size) {target = $1; size = $4;} };
					END {if (index(target, "md") > 0) print "DEVICE=" target}'
			)
	fi
}

# ------------------------ main starts here ---------------------------------

	set -x
	
	[ $# != 6 ] && usage && exit 1
	
	DEVICE=$1

	if [ "$2"x = "like"x ]; then
		get_brick_dev $DEVICE
	elif [ "$2"x != "exact"x ]; then 
		echo "Type value should not be $2." >> $DEPLOYGLUSTERLOG
		exit 2
	fi

	echo $DEVICE >> $DEPLOYGLUSTERLOG

	for mountpoint in `df |grep "export/kylin"|awk '{print $6}'`;do 
		umount $mountpoint
		sleep 2
	done
	# umount device when existing a windows filesystem
	for mountwindows in `df |grep "$DEVICE"|awk '{print $1}'`;do
		umount "$mountwindows"
		sleep 2
	done
	TARGETDIR=
	if [ $3 = 1 ];then
		parted -s $DEVICE mktable gpt
		TARGETDIR="/export/kylin"
	else
		TARGETDIR="/export/kylin"$3
	fi
	mkdir -p $TARGETDIR
	sleep 2
	parted $DEVICE mkpart primary xfs $5 $6 
	sleep 2
	parted $DEVICE name $3 $4
	sleep 2
	if [ "$1"x = "md"x ]; then
		mkfs.xfs -f ${DEVICE}p$3
	else
                mkfs.xfs -f ${DEVICE}$3
	fi

	#try to find UUID of FS
	UUID=
	eval $(blkid |grep "${DEVICE}.\{0,1\}$3"|cut -d ' ' -f 2)

	echo "UUID=$UUID will be mounted to $TARGETDIR" >>  $DEPLOYGLUSTERLOG

	if [ -n UUID ]; then
		if [ $3 = 1 ]; then
			sed -i '/export\/kylin/d' /etc/fstab
			sed -i '$a UUID='"$UUID"' /export/kylin   xfs   defaults  0 0' /etc/fstab
		else
			sed -i '/export\/kylin'"$3"'/d' /etc/fstab
			sed -i '$a UUID='"$UUID"' '"$TARGETDIR"'   xfs   defaults  0 0' /etc/fstab
		fi
	fi
	sleep 5
	mount -a


