
#!/bin/bash

################################################################################################################
###
###  This script removes old data and logs in backup directory.
###
###  You must be the owner of the JaguarDB server process to run this script.
###
###  This is called by jaguar server every day.
###
################################################################################################################

function delfiles
{
    tdir=$1
    retention=$2

    pdir=`dirname $tdir`
    rdir=`basename $tdir`
    find "$pdir" -maxdepth 1 -name "$rdir" -type d -mtime +"$retention" -exec /bin/rm -rf {} +
}


###################################### main #########################################

shopt -s extglob

me=`whoami`

if [[ "x$me" = "xroot" ]]; then
    echo "You cannot run as root or sudo. Run the script as the JaguarDB owner."
    exit 1
fi

if [[ -f "$HOME/.jaguarhome" ]]; then
    JAGUAR_HOME=$(cat "$HOME/.jaguarhome")
else
    JAGUAR_HOME="$HOME"
fi

if [[ -z $JAGUAR_HOME ]]; then
    echo "JAGUAR_HOME is empty, quit"
    exit 10
fi

if [[ "x$JAGUAR_HOME" = "x/" ]]; then
    echo "JAGUAR_HOME is /, quit"
    exit 20
fi


jagowner=`stat -c '%U' $JAGUAR_HOME`
if [[ "x$me" = "x$jagowner" ]]; then
    echo "OK, you are the owner of $JAGUAR_HOME"
else
    echo "!!! You are not the owner of $JAGUAR_HOME  Quit now"
    exit 1
fi


retention_nameval=`grep SNAPSHOT_RETENTION_DAYS $JAGUAR_HOME/conf/server.conf |grep -v '#'`
if [[ -z $retention_nameval ]]; then
    ((retention=30))
else
    retention=`echo $retention_nameval|cut -d'=' -f2`
fi



periods="15min hourly daily weekly monthly"

for tm in $periods; do
    #echo "ls -d $JAGUAR_HOME/backup/$tm/2???-*"
    bkdirs=`/bin/ls -d $JAGUAR_HOME/backup/$tm/2[0-9][0-9][0-9]-[0-9][0-9]-* 2>/dev/null`
    for bkdir in $bkdirs; do
        if [[ ! -z $bkdir ]]; then
            dn=`basename $bkdir`
            delfiles "$JAGUAR_HOME/backup/$tm/$dn" $retention
        fi
    done
done

