#!/usr/bin/ruby -Ke

require 'rice/irc'
require 'rice/observer'
require 'urb'
require 'nkf'
require 'md5'
require 'drb/drb'

$:.unshift('/path/to/rwiki-dir')
require 'rw-lib'

DRb.start_service('druby://localhost:8471')

NICK = 'rwiki-gw'
USER = ENV['USER'] || ENV['USERNAME'] || ENV['LOGNAME'] || NICK
REAL = 'rice/RWiki gateway'

CHANNEL = '#ricetest'

MU_INDEX_PAGE = 'トピック'
# http://ukai.org/mu/draft-ukai-mu-protocol-02.txt
MU_LINE_PATTERN = /\A
                   ([\x1B\x21-\x7E]+)
                   [ \t]+
                   (#{URb::REGEXP::PATTERN::X_ABS_URI})
                   [ \t]+
                   ([\x1B\x21-\x7E]+)
                  \z/xon

Thread.abort_on_exception = true

o = RICE::SimpleClient.new(NICK, USER, REAL, nil, CHANNEL)
c = RICE::Connection.new('localhost', 9999)
c.add_observer(o)

def o.response_for_privmsg(subject, message)
  nick = message.prefix.scan(/^[^!]+/o)[0]
  chan = message.params[0]
  text = message.params[1..-1].join(' ')

  m = MU_LINE_PATTERN.match(text)
  return unless m

  @rwiki ||= DRbObject.new(nil, 'druby://localhost:8470')

  mu_prefix = m[1]
  mu_comment = m[-1]
  url = m[2]

  title = NKF::nkf('-e', mu_prefix + ' ' + mu_comment)
  rwiki_name = MD5.new(url).hexdigest

  rwiki_page = @rwiki.page(rwiki_name)
  if rwiki_page.empty?
    rwiki_page.src = "
= ((<#{title}|URL:#{url}>)) (((<mu:#{rwiki_name}>)))

  * ((<URL:#{url}>))
  * posted by #{nick} on #{Time.now.to_s}
  * このページにリンクする際には
      ((<ほげほげ|mu:#{rwiki_name}>))
    のようにするとよいでしょう。

さあコメントをどうぞ!

"
  end

  rwiki_index = @rwiki.page(MU_INDEX_PAGE)
  rwiki_index.src = "
  * #{title} (((<mu:#{rwiki_name}>)))
" + rwiki_index.src

  subject.push notice chan, "OK <mu:#{rwiki_name}>"
end

def o.response_for_invite(subject, message)
  nick = message.params[0]
  chan = message.params[1]

  if nick == NICK
    subject.push join chan
  end
end

begin
  c.start
rescue RICE::Connection::Closed
  sleep 30
  retry
end

