#!/bin/bash

BKP_DIR=/var/backups/eehosting-backup/redis
#REDIS_SOCKET=/var/run/redis/redis.sock
REDIS_DUMP_FILE=/var/lib/redis/dump.rdb
DATE=`date +%Y%m%d-%HH%M`

EXIT=0
EXIT_MSG=""

if [ ! -d $BKP_DIR ]
then
	mkdir $BKP_DIR
	chown redis:redis $BKP_DIR
	chmod 750
fi

cd $BKP_DIR
if [ $? -ne 0 ]
then
	echo "Unable to chdir to $BKP_DIR" >&2
	exit 1
fi

res=""
if [ -n "$REDIS_SOCKET" ]
then
    res=$( redis-cli -s "$REDIS_SOCKET" save )
else
    res=$( redis-cli save )
fi

if [ "$res" != "OK" ]
then
	EXIT_MSG="$EXIT_MSG\nError saving redis : $res" >&2
	EXIT=1
elif [ ! -f "$REDIS_DUMP_FILE" ]
then
	EXIT_MSG="$EXIT_MSG\nRedis dump file not found ($REDIS_DUMP_FILE)" >&2
	EXIT=1
else
	bzip2 -c --stdout "$REDIS_DUMP_FILE" > $BKP_DIR/${DATE}-dump.rdb.bz2

	if [ $? -ne 0 ]
	then
		EXIT_MSG="$EXIT_MSG\nError backuping Redis dump file"
		EXIT=1
	fi
fi

find $BKP_DIR -mtime +1 -type f -exec rm -f \{\} \;
if [ $? -ne 0 ]
then
	EXIT_MSG="$EXIT_MSG\nUnable to purge old files"
	EXIT=1
fi

if [ -n "$EXIT_MSG" ]
then
	echo -e $EXIT_MSG >&2
fi
exit $EXIT
