#!/bin/bash
# Brett Kelly 2018
# 45Drives
#----------------
# This script takes a subdirectory of a gluster volume as input and reports back the used, avail and total capacity.
# Assuming the following file structure.
# To get the used capcity of "subdir1" you would run this script as "./glusterdf -v volume01 -d dir1/subdir1"
# To get the used capcity of "dir2" you would run this script as "./glusterdf -v volume01 -d dir2"
# 		/volume01
#			|-dir1
#				|-subdir1
#					\file1
#					\file2
#				|-subdir1
#			|-dir2
#				\fi
#				\file2

usage() { # Help
        cat << EOF
Usage:	glusterdf
	[-d] Specify directory. Mandatory
	[-v] Specify Volume Name. Defaults to Tank
	[-h] Displays this message
EOF
        exit 0
}

checkmount(){
	if [ ! -d $MOUNT ];then
		mkdir $MOUNT
	fi
	if mountpoint -q $MOUNT;then
		:
	else
		mount -t glusterfs localhost:$VOLUME $MOUNT
	fi
}
checkinput(){
	if [ ! -d $MOUNT/$DIR ];then
		echo "Subdirectory $DIR is not present on $VOLUME"
		exit 1
	fi
}
getcapacity(){
	echo "Getting used capcity. This may take some time...."
	USED=$(du -s $MOUNT/$DIR | awk '{print $1}')
	TOTAL=$(df | grep $MOUNT | awk '{print $2}')
	AVAIL=$(expr $TOTAL - $USED )
	_USED=$(expr $USED / $b2gb )
	_AVAIL=$(expr $AVAIL / $b2gb )
	_TOTAL=$(expr $TOTAL / $b2gb )
}
cleanup(){
	umount $MOUNT
}

VOLUME="tank"
MOUNT="/mnt/gluster/tmp"
DIR=""
b2gb=1024000

while getopts 'd:v:h' OPTION; do
	case ${OPTION} in
	d)
		DIR=${OPTARG}
		;;
	v)
		VOLUME=${OPTARG}
		;;
	h)
		usage
		;;
	esac
done

if [ -z $DIR ];then
	echo Directory Required
	exit 1
fi

checkmount
checkinput
getcapacity
echo $VOLUME/$DIR Used: "$_USED"GB Available: "$_AVAIL"GB Total: "$_TOTAL"GB
cleanup
