#!/usr/bin/env ruby

require 'sup'
include Redwood
start
Index.new
Index.load

def get_id(msg)
   in_id = false
   id = ""
   File.open(msg) do |f|
      f.each do |line|
         # /\s*(.*?)\s*/
	 if line =~ /^Message-Id:\s*<(.*?)>\s*$/i
	    return $1
	 elsif line =~ /^Message-Id:\s*$/i
	    in_id = true
         elsif in_id
            if line =~ /<(.*?)>/
	       return $1
            else
	       in_id = false
	    end
	 end
      end
   end
   return nil
end    
	    
def check_ferret(msg, fn, id)
   doc = Index.index.search("message_id:#{id}")
   hits = doc.total_hits
   if hits != 1
      date = File.stat(fn).mtime.to_s
      puts "message: #{msg}"
      puts "  id:    #{id}"
      puts "  date:  #{date}"
   end
end

def check_log(filename)
   File.open(filename) do |f|
      f.each do |line|
         if line =~ /\s*Folder:\s*(\S+)\s+(\d+)/
	    msg = $1
	    size = $2
	    if msg !~ /^vd/ && msg !~ /^rd/
	       fn = "#{ENV['HOME']}/Maildir/#{msg}"
	       id = get_id(fn)
	       # puts "message: #{msg}, size #{size}, id #{id}"
	       check_ferret(msg, fn, id)
	    end
	 end
      end
   end
end

ARGV.each {|arg| check_log(arg)}
