#!/bin/bash
# SHOW GROW RATE
#
# Finds all vClone VMDKs under the current directory,
# and prints out what rate they have grown at to help
# with VDI storage sizing

date2stamp () {
    date --utc --date "$1" +%s
}

stamp2date (){
    date --utc --date "1970-01-01 $1 sec" "+%Y-%m-%d %T"
}

dateDiff (){
    case $1 in
        -s)   sec=1;      shift;;
        -m)   sec=60;     shift;;
        -h)   sec=3600;   shift;;
        -d)   sec=86400;  shift;;
        *)    sec=86400;;
    esac
    dte1=$(date2stamp "$1")
#	echo "D1: $dte1"
    dte2=$(date2stamp "$2")
#	echo "D2: $dte2"
    diffSec=$((dte2-dte1))
    if ((diffSec < 0)); then abs=-1; else abs=1; fi
    echo $((diffSec/sec*abs))
}
 


#
# MAIN
#

BC=`which bc`
if [[ -z "$BC" ]]; then
{
	echo "ERROR: Could not find the program bc in your \$PATH. Install it from http://www.mirrorservice.org/sites/mirror.centos.org/3.9/os/i386/RedHat/RPMS/bc-1.06-15.i386.rpm" >&2
	exit 5
}
fi

if [[ -z "$1" ]]; then
{
	echo "Usage: show-grow-rate <dir>" >&2
	exit 1
}
fi

if [[ ! -d "$1" ]]; then
{
	echo "ERROR: $1 is not a directory" >&2
	exit 2
}
fi

# Check we end with a /
if [[ $1 != */ ]]; then 
{
	SEARCH_DIR="$1/"
}
else
{
	SEARCH_DIR="$1"
}
fi

NOW=`date --utc`
echo "Time of script run,$NOW"
echo "VMX,vClone Disk,Creation,Age (hrs),Size (Mb),Rate (Mb/hr),Rate (Mb/min)"
let MBFACTOR=1024*1024
for vm in `find $SEARCH_DIR -name "*.vmx"`; do
{
	TEMP=`echo $vm | grep -E "source|replica"`	# above search will return all VMs on the DS. Filter out any shadow copies/parents that View has
	NOT_DELTA=$?					# created
	if [[ $NOT_DELTA -eq 0 ]]; then
	{
		continue
	}
	fi

	# Find the vClone disk for this VM
	VDISK=`cat $vm | grep vmdk | grep replica | awk '{print $3}' | awk -F "\"" '{print $2}'`

	# Verify that a -delta file actually exists for the disk
	DIR=`dirname $vm`
	NOEXT=${VDISK%*.vmdk}
	DELTA="$DIR/$NOEXT-delta.vmdk"
	if [[ ! -f $DELTA ]]; then
	{
		continue
	}
	fi

	# We might still be left with replica VMs rather than real user VMs. Take those out too
	TEMP=`echo $DIR | grep "replica-"`
	NOT_REPLICA=$?
	if [[ $NOT_REPLICA -eq 0 ]]; then
	{
		continue
	}
	fi

	# Now we should just be left with real user vClones
	VDISK_PATH=$DIR/$VDISK
	VMDK_CREATION=`date --utc -r $VDISK_PATH`
	AGE_MINS=`dateDiff -m "$VMDK_CREATION" "$NOW"`
	AGE_HRS=`echo "scale=0; $AGE_MINS/60" | $BC`
	SIZE_BYTES=`ls -l $DELTA | awk '{print $5}'`
	SIZE_MB=`echo "scale=2; $SIZE_BYTES/$MBFACTOR" | $BC`
	MIN_RATE=`echo "scale=2; ($SIZE_BYTES/$MBFACTOR)/$AGE_MINS" | $BC`
	HR_RATE=`echo "scale=2; (($SIZE_BYTES/$MBFACTOR)/$AGE_MINS)*60" | $BC`
	
	echo "$vm,$VDISK_PATH,$VMDK_CREATION,$AGE_HRS,$SIZE_MB,$HR_RATE,$MIN_RATE"
}
done

