require "singleton"
require "nkf"

module Apache
  class AutoCharset
    include Singleton

    CHARSETS = Hash.new("iso-8859-1")
    CHARSETS[NKF::JIS] = "iso-2022-jp"
    CHARSETS[NKF::EUC] = "euc-jp"
    CHARSETS[NKF::SJIS] = "shift_jis"

    def handler(r)
      if r.finfo.mode == 0
        return NOT_FOUND
      end
      if r.filename !~ /\.(html|htm)$/
        return DECLINED
      end
      open(r.filename) do |f|
        body = f.read
        enc = NKF.guess(body)
        charset = CHARSETS[enc]
        r.content_type = format("text/html; charset=%s", charset)
        r.headers_out["Content-Length"] = body.length.to_s
        r.send_http_header
        r.print(body)
        return OK
      end
    end
  end
end

