#!/usr/bin/ruby
require 'rubygems'
require 'nokogiri'
require 'uri'
require 'net/http'
$site_prefix = 'http://masaru.org/wp/'

class TDiaryHtmlParser
  def initialize
    @articles = []
    @ymd = nil
  end
  def check_file_exist(url)
    res = Net::HTTP.get_response(URI.parse(url))
    if res.code != "200"
      STDERR.puts "Failed to get #{url}  : #{res.code}"
    end
  end
  def rewrite_content(node)
    ymd = @article_year + @article_month + @article_day

    node.xpath("a").each do |anchor|
      anchor.xpath("@href").each do |url|
	us = url.to_s
	if us.match(/.\/(images|photos)\/#{ymd}[^\/]+$/) 
	  # for image tag
	  basename = File::basename(us)
	  u = "#{$site_prefix}/wp-content/uploads/#{@article_year}/#{@article_month}/#{basename}"
	  check_file_exist(u)
	  url.value = u
	elsif us.match(/.\/(20[0-9]{2})([01][0-9])([0123][0-9]).html\#p[0-9]+$/)
	  # for inside link
	  y,m,d =$1,$2,$3
	  url.value = "#{$site_prefix}/archives/date/#{y}/#{m}/#{d}"
	end
      end
    end

    node.css("img").each do |img|
      img.xpath("@src").each do |url|
	us = url.to_s
	if us.match(/^\.\/(images|photos)\/.*#{ymd}[^\/]+$/) 
	  basename = File::basename(us)
    	  u = "#$site_prefix/wp-content/uploads/#{@article_year}/#{@article_month}/#{basename}"
	  check_file_exist(u)
	  url.value = u
	end
      end
    end
  end

  def parse(file)
    doc = Nokogiri::HTML(open(file))
    doc.css('div.section').each do |section|
       head = section.css('h3').shift
       next if head.nil?
       href =  head.xpath('a/@href')[0].content
       subject = head.xpath("text()")[0].content
       uri = URI.parse(href)
       basename = File::basename(uri.path)
       #article_number = uri.fragment()
       unless basename.match(/^([0-9]{4})([01][0-9])([0-3][0-9])/)
	 STDERR.puts "unknown date from basename #{basename}"
       end
       @article_year, @article_month, @article_day = $1, $2, $3

       # pickup body
       skip = true
       body = ""
       section.children.each do |child|
	 if skip && child.name == "h3"
	   skip = false
	 elsif skip == false
	   rewrite_content(child)
	   body += child.to_s
	 end
       end

       print <<_END_
AUTHOR: Masaru Yokoi
TITLE: #{subject}
STATUS: Draft
ALLOW COMMENTS: 1
ALLOW PINGS: 1
DATE: #{@article_year}/#{@article_month}/#{@article_day}
-----
BODY:
#{body}
-----
--------
_END_
    end
  end
end

ARGV.each do |arg|
  parser = TDiaryHtmlParser.new
  parser.parse(arg)
end
