#!/bin/sh

# Daily jobs required for JFFNMS
if [ ! -d /usr/share/jffnms ] ; then
  exit 0
fi

# Source the defaults file
if [ -r /etc/default/jffnms ]; then
. /etc/default/jffnms
fi


# Delete temporary images older than a day
deltmpimages()
{
    # Try to find it in the customised file first
    IMAGEPATH=`cat /etc/jffnms/jffnms.conf 2>/dev/null | perl -e 'while (<>) { if ($_ =~ /^\s*images_real_path\s*=\s*(\S+)/) { print "$1\n"; exit 0; }}'`
    if [ -z "$IMAGEPATH" ] ; then
        IMAGEPATH=`cat /etc/jffnms/jffnms.conf.defaults 2>/dev/null | perl -e 'while (<>) { if ($_ =~ /^\s*images_real_path:default\s*=\s*(\S+)/) { print "$1\n"; exit 0; }}'`
    fi
    if [ -z $IMAGEPATH ]; then
        echo "images_real_path not found in jffnms configuration files jffnms.conf or jffnms.conf.defaults"
		return
    fi
    # Delete any .png .dot and .map files older than a day
	if [ -d "$IMAGEPATH" ]; then
    	find $IMAGEPATH -type f  -mtime +1 -regex '.*\.\(png\|dot\|map\)$' -exec rm {} \;
	fi
}

# Delete temporary engine files older than a day
deltmpengine()
{
    # Try to find it in the customised file first
    ENGINEPATH=`cat /etc/jffnms/jffnms.conf 2>/dev/null | perl -e 'while (<>) { if ($_ =~ /^\s*engine_temp_path\s*=\s*(\S+)/) { print "$1\n"; exit 0; }}'`
    if [ -z "$ENGINE" ] ; then
        ENGINEPATH=`cat /etc/jffnms/jffnms.conf.defaults 2>/dev/null | perl -e 'while (<>) { if ($_ =~ /^\s*engine_temp_path:default\s*=\s*(\S+)/) { print "$1\n"; exit 0; }}'`
    fi
    if [ -z $ENGINEPATH ]; then
        echo "engine_temp_path not found in jffnms configuration files jffnms.conf or jffnms.conf.defaults"
		return
    fi
	# Delete any .log files older than a day
	if [ -d "$ENGINEPATH" ]; then
        find $ENGINEPATH -type f  -mtime +1 -regex '.*/[0-9a-f]+\.log$' -exec rm {} \;
	fi
}

deloldlogs()
{
    # Find the log directory out of configuration file
    LOGPATH=`cat /etc/jffnms/jffnms.conf 2>/dev/null | perl -e 'while (<>) { if ($_ =~ /^\s*log_path\s*=\s*(\S+)/) { print "$1\n"; exit 0; }}'`
    if [ -z $LOGPATH ] ; then
        LOGPATH=`cat /etc/jffnms/jffnms.conf.defaults 2>/dev/null | perl -e 'while (<>) { if ($_ =~ /^\s*log_path:default\s*=\s*(\S+)/) { print "$1\n"; exit 0; }}'`
    fi

    if [ -z $LOGPATH ]; then
        echo "log_path not found in jffnms configuration files jffnms.conf or jffnms.conf.defaults."
		return
    fi

    # Compress logs older than 2 days
    if [ -z $COMPRESSLOGS ]; then
      COMPRESSLOGS=2
    fi

    # Delete logs older than 7 days
    if [ -z $DELETELOGS ]; then
      DELETELOGS=7
    fi

	if [ -d "$LOGPATH" ]; then
        find $LOGPATH -type f  -mtime +$DELETELOGS -exec rm {} \;

        for fname in `find $LOGPATH -mtime +$COMPRESSLOGS -name '*.log'` ; do
          gzip $fname
        done
	fi
}

#
# START HERE
#

deloldlogs
deltmpimages
deltmpengine
