#!/bin/bash

dir1=/mnt/raid
dir2=/mnt/lvg_storage
dir3=/mnt/storage1
dir4=/mnt/storage2

temp=/tmp/directory-sizes.tmp
output=/var/www/html/directory-sizes.txt

DATE=`which date`
DU=`which du`
SED=`which sed`
AWK=`which awk`
SORT=`which sort`
RM=`which rm`
ECHO=`which echo`
CAT=`which cat`
DIFF=`which diff`
GREP=`which grep`
PRINTF=`which printf`
MAIL=`which mail`

${DU} -h --max-depth=1 ${dir1} | ${SED} -e '$d' -e 's/\/.*\/.*\///g' -e '/^.*lost+found$/d' > ${temp}
${DU} -h --max-depth=1 ${dir2} | ${SED} -e '$d' -e 's/\/.*\/.*\///g' -e '/^.*lost+found$/d' >> ${temp}
${DU} -h --max-depth=1 ${dir3} | ${SED} -e '$d' -e 's/\/.*\/.*\///g' -e '/^.*lost+found$/d' >> ${temp}
${DU} -h --max-depth=1 ${dir4} | ${SED} -e '$d' -e 's/\/.*\/.*\///g' -e '/^.*lost+found$/d' >> ${temp}

${ECHO} -e "Daily Directory Size Report\n" > ${output}
${DATE} >> ${output}
${ECHO} "" >> ${output}
${SORT} -k2,2 ${temp} >> ${output}
${SED} -e '/^.*K\t.*$/d' -e '/^.*M\t.*$/d' ${temp} | ${AWK} '{total += $1} END{print "\n" total " GB Total"}' >> ${output}
${SED} -e '/^.*K\t.*$/d' -e '/^.*M\t.*$/d' ${temp} | ${AWK} '{total += $1} END{print "\n" total/1024 " TB Total"}' >> ${output}

${CAT} ${output} > /var/log/dir_sizes/$(${DATE} +%F)-sizes.log

${ECHO} -e "\n\nChanges From Yesterday\n" >> ${output}
${DIFF} /var/log/dir_sizes/$(${DATE} +%F --date='1 days ago')-sizes.log /var/log/dir_sizes/$(${DATE} +%F)-sizes.log | ${GREP} -iE "(<|>)" | ${SED} -e "1,2d" -e :a -e '$d;N;2,6ba' -e 'P;D' | ${SORT} -k3,3 -k1,1 | ${SED} -e "s/</Old:/g" -e "s/>/New:/g" -e "s/\(New:.*\)/\1\n/g" | ${AWK} '{$1=$1}1' OFS=" " >> ${output}
${DIFF} /var/log/dir_sizes/$(${DATE} +%F --date='1 days ago')-sizes.log /var/log/dir_sizes/$(${DATE} +%F)-sizes.log | ${GREP} "Total" | ${GREP} -iE "(<|>)" | ${SED} -e "s/</Old:/g" -e "s/>/New:/g" -e "s/\(New:.*\)/\1\n/g" | ${AWK} '{$1=$1}1' OFS=" " >> ${output}

${PRINTF} "%b" "`${CAT} ${output}`" | ${MAIL} -s "Mirror - Daily Directory Size Report" root

${RM} ${temp}
