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

log_dir="/home/jocke/.imapfilter"
log_dir_old="/home/jocke/.imapfilter/old"
date_start=""
date_end=""
unseen=""
initial_unseen=""
unseen_threshold=10
start_imapfilter=1
fix_imapfilter=0
first_unseen=0

weranfor(){
	seconds=""
	minutes=""
	hours=""
	days=""

	total_seconds="$((date_end - date_start))"

	let "seconds = $total_seconds % 60"
	let "minutes = $total_seconds / 60 % 60"
	let "hours = $total_seconds / 60 / 60 % 24"
	let "days = $total_seconds / (60 * 60 * 24)"

	echo "imapfilter ran for $days day(s), $hours hour(s), $minutes minute(s) and $seconds second(s) before it crashed."
}

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

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

		echo "Moving old logfiles to $log_dir_old..."
		mv $log_dir/debug.* $log_dir_old 2> /dev/null
		mv $log_dir/imapfilter.log $log_dir_old/$logfile 2> /dev/null

		if [ $fix_imapfilter -eq 1 ]; then
			# We need to move emails before starting imapfilter again

			echo "We need to move some emails before we start imapfilter in daemon mode."

			imapfilter -c /home/jocke/imapfilter/config-fix.lua

			fix_imapfilter=0
		fi

		# Start imapfilter
		echo "Starting imapfilter in daemon mode..."
		imapfilter -c /home/jocke/imapfilter/config.lua -l /home/jocke/.imapfilter/imapfilter.log -d

		start_imapfilter=0
		first_unseen=1
	fi
	
	# Sleep for a short while, before we check stuff
	sleep 10
	
	if cat $log_dir/debug.* $log_dir/imapfilter.log|grep -qE "( BAD | EOF )"; then
		# We need to restart
		echo "Shit! Something went wrong! We need to restart imapfilter."

		# How long did we run before crash?
		date_end="`date "+%s"`"
		weranfor	

		# First, find PID of imapfilter
		pid=`ps -eo pid,args | grep -i "/home/jocke/imapfilter/config.lua" | grep -viE "(grep|screen|bash)" | cut -c1-6 | perl -wple 's| ||g'`
		
		# Then we kill it
		echo "Killing imapfilter with PID $pid..."
		kill $pid &

		# Then we need to start imapfilter again
		start_imapfilter=1
	fi
	
	# Get latest UNSEEN-value
	latest_debugfile=`ls -1t $log_dir/debug.*|head -1`
	unseen=`cat $latest_debugfile | grep -E "\* [0-9]* RECENT" | tail -1 | perl -wple 's,\*,,;s,RECENT,,;s,\s+,,g'`

	if [ ! -z $unseen ]; then
		# Variable $unseen has a value
	
		if [ $first_unseen -eq 1 ]; then
			# This is the first UNSEEN-value, hence it becomes our initial UNSEEN-value

			echo "This is the first UNSEEN-value we got, so it's stored as our "'$initial_unseen'"-variable."

			initial_unseen="$unseen"
			first_unseen=0
		else
			# This is not the first UNSEEN-value we see
			# We should check if it's been incremented compared to our $initial_unseen-variable
			# If $unseen-$initial_unseen >= $unseen_threshold, then we would like to restart
			# However, we would also like to run imapfilter once with 'imapfilter -c /homee/jocke/imapfilter/config-fix.lua', so that mails get moved
		
			if [ $(($unseen - $initial_unseen)) -gt $unseen_threshold ]; then
				# We should kill imapfilter, run 'imapfilter -c $HOME/imapfilter-fix.lua' first, and then start imapfilter again
			
				echo ""'$unseen'"=$unseen"
                		echo ""'$initial_unseen'"=$initial_unseen"
                		echo ""'$unseen_threshold'"=$unseen_threshold"
				echo "UNSEEN-value too high. We need to restart + run fix."

				# How long did we run before crash?
                		date_end="`date "+%s"`"
                		weranfor
				
				fix_imapfilter=1
				start_imapfilter=1
			fi
		fi
	else
		echo "We tried to get the UNSEEN-value, but none was found. This should only happen when the program starts."
	fi
done
