#!/usr/bin/env ruby

require "net/imap"
require "date"
require "base64"
require "erb"

class ::String
	def shorten(max, ellipsis)
		if length > max
			self[0..(max - ellipsis.length - 1)] + ellipsis
		else
			ljust(max)
		end
	end

	def xml_encode
		gsub('&', '&lt;').gsub('<', '&lt;')
	end
	
	def decode_email
		gsub!(/=\?([^?]+)\?([QqBb])\?([^?]+)\?= */) do
			encoding_name = $1
			encoding_type = $2
			content = $3
			
			# Some encoding names used in mails are not recognized by Ruby
			encoding_name = 'iso-8859-1' if encoding_name == 'ISO'

			if encoding_type =~ /b/i
				content = Base64.decode64(content)
			end
			
			content.gsub!('_', ' ')
			content.gsub!(/(=[0-9A-F][0-9A-F])+/) do |bytes|
				bytes.split('=').compact.map{ |byte| byte.to_i(16) }.pack("c*")
			end
			content
		end
		self
	end
end

#@response['Content-Type'] = @request['HTTP_USER_AGENT'] =~ /Mozilla/ ? 'text/xml' : 'application/atom+xml; charset=UTF-8'

puts "Content-Type: text/plain; charset=UTF-8"
puts
puts "En cours..."
return

begin 
	imap = Net::IMAP.new("localhost", 993, true)# { :verify_mode => OpenSSL::SSL::VERIFY_NONE })
	imap.authenticate("LOGIN", "genezys", "0xdeadb33f")
	imap.examine("INBOX")

	message_uids = imap.search('ALL')
	messages = imap.fetch(message_uids, "ALL")
	
	puts "Content-Type: text/xml;encoding=UTF-8"
	puts
	puts ERB.new(DATA.read).result(binding)

ensure 
	imap.close unless imap.nil? 
end

__END__
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Inbox</title>
<link href="http://example.org/"/>
<updated>2010-05-13T18:30:02Z</updated>
<author>
	<name>Paul Martin</name>
	<email>paulmartin@example.com</email>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6</id>
<% 
	messages.each_with_index do |message, index|
		envelope = message.attr["ENVELOPE"]
	
		date = DateTime.strptime(envelope.date, "%a, %d %b %Y %H:%M:%S %Z") rescue  
			DateTime.strptime(envelope.date, "%d %b %Y %H:%M:%S %Z") rescue 
			nil

		from = envelope.from[0]
		author = from.name || "#{from.mailbox.decode_email}@#{from.host.decode_email}"
		subject = envelope.subject
%>
<entry>
	<title><%= subject.decode_email.xml_encode %></title>
	<link href="http://example.org/2003/12/13/atom03"/>
	<id>urn:message-<%= index.to_s.xml_encode %></id>
	<updated><%= date.strftime('%Y-%m-%dT%H:%M:%S%Z').xml_encode %></updated>
</entry>

<% end %>
</feed>
