#!/usr/local/bin/ruby
#  encoding: utf-8
#  d_google.rb

#  Created by midori on 2006-10-25.
#  Copyright (c) 2006. All rights reserved.
#  You can distribute/modify this program under the terms of the Ruby License.
#  Last change: 2006-10-25.

class GoogleSiteMap
  include MakeXML
  include ReadWrite
  def initialize(myhash)
    @pub_dir = myhash["dir_pub"] #
    @path_google_sitemap = File.join(@pub_dir, "google_sitemap.xml")
    @pub_url ="http://www.midore.net"
  end
  def make_google_sitemap(prune_list, skip_file)
    list_html_page = p_get_html(prune_list)
    # delete skip_files ex; 404.html and private.html
    r_skip_file = Regexp.new(skip_file.join("|"))
    list_html_page.delete_if {|x| x =~ r_skip_file}
    google_xml = p_make_googlexml(p_make_hash(list_html_page))
    return google_xml
  end
  private
  def p_get_html(prune_list)
    require "find"
    out_dir = Regexp.new(prune_list.join("|"))
    ans_list = Array.new
    Find.find(@pub_dir) do |f|
      ans_list << f if f.to_s=~ /\.html/
    Find.prune if f =~ out_dir
    end
    return ans_list
  end
  
  def p_make_hash(list_html_page)
    require "time"
    my_hash_element = Hash.new; n = 0
    list_html_page.each{|html|
      child_hash = Hash.new
      child_hash['loc'] = html.gsub(@pub_dir, @pub_url)
      a_time = File.atime(html) if FileTest.exist?(html)
      u_rfctime = Time.parse(a_time.to_s).strftime("%Y-%m-%d")
      child_hash['lastmod'] = u_rfctime
      child_hash['changefreq'] = "daily"
      if html =~ /\/index\.html/
        child_hash['changefreq'] = "monthly"
      end
      child_hash['priority'] = 0.6
      my_hash_element[n] = child_hash
      n += 1
    }
    return my_hash_element
  end
  def p_make_googlexml(my_hash_element)
    doc = m_make_new_xml("urlset"); docroot = doc.root
    docroot.add_attribute("xmlns", "http://www.google.com/schemas/sitemap/0.84"); docroot.add_text("\n\n")
    my_hash_element.each{|key, value|
      newitem = REXML::Element.new("url")
      newitem.add_text("\n")
      value.each{|k, v| ek = newitem.add_element(k); ek.add_text(v.to_s); newitem.add_text("\n")}
      docroot.add_element(newitem); docroot.add_text("\n")
      }
    google_xml = doc.to_s
    p_write_googlexml(google_xml)
    return google_xml
  end
  def p_write_googlexml(google_xml)
    if FileTest.exist?(@path_google_sitemap)
      cash_trash_file = @path_google_sitemap + ".old"
      File.rename(@path_google_sitemap, cash_trash_file)
    end
    m_write_file(@path_google_sitemap, google_xml)
  end
end

