#!/bin/bash

# Written by Remco Hage
# RealOpenIT

# Citrix datastore size check
DS_NAME="$1"
WARNING="90"
CRITICAL="95"

# Storage
UUID=$(xe sr-list params=all | grep -v name-description | grep -v allowed-operations | grep -v current-operations | grep -v VDIs | grep -v PBDs | grep -v virtual-allocation | grep -v type | grep -v shared | grep -v other-config | grep -v sm-config | grep -v blobs | grep -v local-cache-enabled | grep -v tags | grep -A 4 $DS_NAME |  tr '\n' ' ' | sed -e 's/://g')

# VARIABLES
NAME=$(echo $UUID | awk '{ print $8 $9 }')
HOST=`echo $UUID | awk '{ print $13 }'`
ALLOCATION=$(echo $UUID | awk '{ print $17}')
ALLOCATION_GB=$(echo "scale=2; $ALLOCATION / 1024 / 1024 / 1024" | bc)
TOTAL_SIZE=$(echo $UUID | awk '{ print $21}')
TOTAL_SIZE_GB=$(echo "scale=2; $TOTAL_SIZE / 1024 / 1024 / 1024" | bc)

# Calculation percentage
PROCENT1=$(echo "scale=20; 100/"$TOTAL_SIZE"" | bc)
TOTALPROCENT=$(echo "scale=20; $PROCENT1*$ALLOCATION" | bc | cut -c 1-2)
LEFT=$(echo "scale=0; "$TOTAL_SIZE"-"$ALLOCATION"" | bc)
LEFT_GB=$(echo "scale=2; $LEFT / 1024 / 1024 / 1024" | bc)

# test critical

		if [[ "$CRITICAL" -le "$TOTALPROCENT" ]]; then
		echo "CRIT: "$HOST": Used disk-space:"$ALLOCATION_GB"/"$TOTAL_SIZE_GB"GB LEFT: "$LEFT_GB"GB PERCENTAGE: "$TOTALPROCENT""	
		exit 2
		elif [[ "$WARNING" -le "$TOTALPROCENT" ]]; then
		echo "WARN: "$HOST": Used disk-space:"$ALLOCATION_GB"/"$TOTAL_SIZE_GB"GB  LEFT:"$LEFT_GB"GB PERCENTAGE: "$TOTALPROCENT""
			exit 1
		else
		echo "OK: "$HOST": Used disk-space:"$ALLOCATION_GB"/"$TOTAL_SIZE_GB"GB LEFT:"$LEFT_GB"GB PERCENTAGE: "$TOTALPROCENT""
			exit 0
		fi
		;;

