require 'net/http'
require 'timeout'
Net::HTTP.version_1_2


class ExcusePlugin < Plugin
  def help(plugin, topic="")
    "excuse => supply a random excuse"
  end
  def privmsg(m)

    if(ENV['http_proxy'])
      if(ENV['http_proxy'] =~ /^http:\/\/(.+):(\d+)$/)
        proxy_host = $1
        proxy_port = $2
      end
    end

    Thread.new do
      resp = nil
      begin
        timeout(6) {
          http = Net::HTTP.new("bofh.engr.wisc.edu", 666, proxy_host, proxy_port)
          http.start {|http|
            resp = http.get("/")
          }
        }
      rescue
        m.reply "the excuse server is unreachable (timeout) :("
        return
      end

      if resp.body.empty?
        m.reply "the excuse server is unreachable :("
        return
      else
        resp.body.each_line {|l|
          if(l =~ /^Your excuse is: (.*)$/)
            m.reply $1
            return
          end
        }
      end

      m.reply "the excuse server is unreachable :("
    end
  end
end

plugin = ExcusePlugin.new
plugin.register("excuse")

