#!/usr/local/bin/bash

CACHEDIR='/var/www/icinga-web/app/cache'
EXIT=0
NOTHING=true

function msg_start {
	echo -n "$1 ... "
}

function msg_result {
	EXIT=$?

	if [[ $EXIT -gt 0 ]]; then
		echo "fail"
	else
		echo "ok"
	fi

	NOTHING=false
}

if [ ! -w "$CACHEDIR" ]; then
	echo "You don't have filesystem permissions to clear the cache in $CACHEDIR!" >&2
	exit 1
fi

if [[ ! -e $CACHEDIR ]]; then
	echo "Cachedir '$CACHEDIR' does not exist!"
	exit 1
fi

echo "Cachedir: $CACHEDIR"

CCDIR="$CACHEDIR/config $CACHEDIR/content $CACHEDIR/CronkTemplates $CACHEDIR/Squished"

for CUR_CDIR in $CCDIR; do
	CC_FILES=$(ls $CUR_CDIR/* 2>/dev/null | wc -l)
	if [[ $CC_FILES -gt 0 ]]; then

		CUR_CNAME=$(basename $CUR_CDIR)

		msg_start "Deleting cache from $CUR_CNAME ($CC_FILES files)"

		find $CUR_CDIR/ -type f -exec rm -f {} \;

		msg_result

	fi
done

if [[ $NOTHING == true ]]; then
	echo "Cache already purged!"
fi

exit $EXIT
