#!/usr/bin/ruby

require 'inotify'

LED_FILE = "/proc/acpi/ibm/light"

$maildir = "/home/jek/Mail"
$mboxes = ["mbox", "livejournal", "mikki", "velo", "debian-russian", "espam"]

class MboxNotifier
  def notify(mbox_name, wd,  event)
  end
end

class LedBlinkNotifier < MboxNotifier
  def notify(mbox_name, wd, event)
    led_state = IO.read(LED_FILE).split()[1]
    1.upto(wd * 2) { |i|
      led_state = led_state == 'off' ? 'on' : 'off'
    p led_state
      system("sudo sh -c 'echo #{led_state} > #{LED_FILE}'")
      sleep(0.1)
    }
  end
end

class MboxWatcher
  def initialize(mboxes)
    @i = Inotify.new
    @watches = {}
    @notifiers = {}
    @notifiers[:all] = []

    mboxes.each {|mbox|
      begin
	wd = @i.add_watch(mbox, Inotify::CLOSE_WRITE)
	@watches[wd] = mbox
	@notifiers[mbox] = []
	p "File #{mbox} has been added: #{wd}"
      rescue
	puts "File #{mbox} has not been added: #{$!}"
      end
    }
  end

  def run
    t = Thread.new do
      @i.each_event do |ev|
	f = @watches[ev.wd]
	if $mboxes.include?(File.basename(f)) and File.mtime(f) > File.atime(f)
	  p f
	  @notifiers[:all].each {|n| n.notify(f, ev.wd, :changed)}
	  @notifiers[f].each {|n| n.notify(f, ev.wd, :changed)}
	end
      end
    end

    t.join
  end

  def add_notifier(mboxes, notifier)
    unless mboxes.kind_of?(Array)
      @notifiers[mboxes] << notifier
    else
      mboxes.each {|m|
	@notifiers[m] << notifier
      }
    end
  end
end

watcher = MboxWatcher.new($mboxes.map {|m| File.join($maildir, m)})
n = LedBlinkNotifier.new
watcher.add_notifier(:all, n)
watcher.run

