def mysql opts, stream
  IO.popen("mysql #{opts}", 'w') { |io| io.puts stream }
end

mysql "-u root", <<-END
  drop database if exists weblog_development;
  create database weblog_development;
  grant all on weblog_development.* to #{`id -un`.strip}@localhost;
END

mysql "weblog_development", <<-END
  drop table if exists entries;
  create table entries (
    id int not null auto_increment,
    atomid varchar(45),
    title varchar(100),
    updated datetime,
    summary text,
    content text,
    parent_id int,
    primary key(id)
  )
END

require 'rubygems'
require_gem 'activerecord'

ActiveRecord::Base.establish_connection(
  :adapter  => "mysql",
  :database => "weblog_development",
  :socket   => "/var/run/mysqld/mysqld.sock"
)

class Entry < ActiveRecord::Base
  acts_as_tree :order=>"updated"
end

require 'rexml/document'

class REXML::Element
  def atomtext

    return nil if attribute("src")

    type = attribute("type")
    case type && type.value

      when "xhtml"
        throw "missing xhtml:div" if elements[1].name != "div"
        return elements[1].to_a.to_s.strip

      when "html"
        return text.strip

      when "text", nil
        return to_a.to_s.strip

      when /^text\//i, /\+xml$/i, /\/xml$/i
        return to_a.to_s.strip

      else
        require 'base64'
        return Base64.decode64(text.gsub(/\s/,''))

    end
  end
end

ns = {"atom" => "http://www.w3.org/2005/Atom"}
for feed in ARGV do
  puts feed
  doc = REXML::Document.new open(feed) {|file| file.read }
  feed=doc.find {|element| element.name="entry"}

  parent = nil
  for entry in feed.elements do
    next unless entry.namespace == ns['atom'] and entry.name=='entry'

    post = parent ? parent.children.create : Entry.new

    for child in entry.elements do
      next unless child.namespace == ns['atom']
      case child.name
        when 'id'      then post.atomid  = child.text
        when 'title'   then post.title   = child.atomtext
        when 'summary' then post.summary = child.atomtext
        when 'content' then post.content = child.atomtext
        when 'updated' then post.updated = child.text
      end
    end

    post.save!
    parent = post unless parent
  end
end

Entry.roots.each { |entry|
  puts "#{entry.updated.iso8601} #{entry.children.count} #{entry.title[0..49]}"
}
