#!/bin/bash
# Script that monitors imapfilter for errors, and restarts it if neccesary

imapfilter_dir="/home/jocke/imapfilter/imapfilter-2.2.2"
imapfilter_cmd="cd $imapfilter_dir && ./imapfilter -c /home/jocke/imapfilter/config.lua -l /home/jocke/.imapfilter/imapfilter.log -d"
log_dir="/home/jocke/.imapfilter"
log_dir_old="/home/jocke/.imapfilter/old"

start_imapfilter=1

while true; do
	# Start imapfilter
	if [ $start_imapfilter -eq 1 ]; then

		# Move old logfiles & debug
		date=`date +%Y-%m-%d`
		logfile="$date-imapfilter.log"

		mv $log_dir/debug.* $log_dir_old 2> /dev/null
		mv $log_dir/imapfilter.log $log_dir_old/$logfile 2> /dev/null

		# Start imapfilter
		cd $imapfilter_dir && ./imapfilter -c /home/jocke/imapfilter/config.lua -l /home/jocke/.imapfilter/imapfilter.log -d

		start_imapfilter=0
	fi
	
	# Sleep for a short while, before we check stuff
	sleep 10
	
	if cat $log_dir/debug.* $log_dir/imapfilter.log|grep -E "( BAD | EOF )"; then
		# We need to restart
		# First, find PID of imapfilter
	
		pid=`ps -eo pid,args | grep imapfilter | grep -viE "(grep|screen) | cut -c1-6 | perl -wple 's| ||g'`
		
		# Then we kill it
		kill $pid

		# Then we need to start imapfilter again
		start_imapfilter=1
	fi
done