#!/usr/bin/env ruby
# 表題: 塚原大輔用の rd2 実行スクリプト
# 履歴: 2004/03/15 : やまだ由さんのスクリプトをぱくって作成
require '/home/daktu32/lib/rd_filter-d'
require '/home/daktu32/lib/rd_pagebreak-d'
include Rdfilter
$KCODE = "e"


# rd が html より更新時刻が遅い時, 実行する
def rd2start_all
  Dir.foreach(Dir.pwd) { |infile|
    count = 0
    if infile =~ /.rd$/

      # rd, html 更新時刻比較
      html = File.basename(infile, ".rd") + ".html"
      htmlnum = File.basename(infile, ".rd") + "_001.html"
      if File.exist?(html)
	count = 1 if File.mtime(infile) > File.mtime(html)
      else
	if File.exist?(htmlnum)
	  count = 1 if File.mtime(infile) > File.mtime(htmlnum)
	else 
	  count = 1
	end
      end

      # 実行
      if count == 1
	print infile + " start. \n"
	rd2start(infile)
      end

    end
  }
end

# 実行
def rd2start(infile)

  # 現在の rd をとっておく
  File.rename(infile, "tmp.rd")
  # フィルター
  outfile_ary = filter_io_daktu32(infile)

  # rd2 実行
  outfile_ary.each { |file|
    html = File.basename(file, ".rd") + ".html"
    `#{$rd2html} #{file} > #{html}`
    # ひとつ上のディレクトリに html をコピー
    open(html) {|source|
      open("../#{html}", "w") {|dest| 
	dest.write(source.read) 
      }  
    }
  }
  
  # 元の rd の復帰
  File.rename("tmp.rd",infile)

end

# フィルター (tex, ruby, pagebreak)
def filter_io_daktu32(infile)
    rdfilter_make("tmp.rd",infile)
    outfile_ary = rdpagebreak_make(infile)
    File.delete(infile) unless outfile_ary.size == 1
  return outfile_ary
end



########################################################
if $0 == __FILE__

  
rd2_daktu32_data = <<EOF
#!/usr/bin/env ruby
# 表題: 塚原大輔用の rd2 実行スクリプト
# 履歴: 2004/03/15 : やまだ由さんのスクリプトをぱくって作成
require '/home/daktu32/lib/rd2-daktu32'

# rd のコマンド

# dennou-t
 $rd2html =  'rd2 --r /home/daktu32/lib/ruby/site_ruby/1.6/rd/rd2html-ext-lib --with-part=html:include --out-code=euc --with-css=../include/dcchart.css  --ref-extension --native-inline'

# main()

Dir.chdir(Dir.pwd)
File.delete("tmp.rd") if File.exist?("tmp.rd")

if ARGV[0] == nil
  rd2start_all
else
  rd2start(ARGV[0])  
end


EOF

wfile = open("#{Dir.pwd}/rd2-make-d.rb","w") 
wfile.print rd2_daktu32_data
wfile.close
print "rd2-make-d.rd create\n"

end

