#!/usr/bin/env ruby
# $Id: autoimg,v 2.3.4.2 2016/01/04 02:26:29 yuuji Exp $
#

=begin
-- autoimg -- ưŪ˲ե(*.jpg, *.png)õ <img src..> !


  ɤǤȤɤ󤫤ʬޤؤ󡣴ˡWeb
  ٱġ mkdiary.rbפĤƤ͸ĤƤ͡
  (http://www.gentei.org/~yuuji/diary/mkdiary/manual.html)

Ĥ

  * ᥤ⡼(mkdiary.rb -s) ƤӽФ
    Ĥޤꡢ~/.mkdiaryrc 

	bodyfilter=autoimg

    Ƚ񤤤Ƥ⤷body2html ȤȤ߹碌Ȥϡ

	bodyfilter=body2html|autoimg

    ߤ˥ѥ(|)ǷҤ

ᥤν

  źդ롣äΤϤ衣ǡʸϤĤΤ褦˽
  Τʤǡ<img src="hogehoge.jpg" ...> ߤ줿ʬ

	%IMG

  Ƚ񤭤ޤ礦źդ줿ե뤬ưŪõơimg˲
  ⤷ʣβźդ

	%IMG1
	%IMG2

  ߤIMGľźղβܤ򼨤񤳡⤷
  ơΥڡˤϤä㤤ͥĤ̿ΩƤΥڡ
  ˤȤϡͥˤȤ

	%IMG1=ŷΤ褤ͼ

  ߤ˽񤭤ޤ礦img2wwƤǥͥ벽ޤͥ
  CSSǤȤ float ΤǡȤХᥤʸ

	%IMG1=顼700
	ϤäפǤ衼ʸʸϡġġ
	ʸʸϡĤä

	%IMG1=Ч800
	ϤäȤäפǤ衼ʸʸϡġġ
	ʸʸϡĤä¿!

  ʤɤȤȡڡ쥤Ȥ

	+------------+
	| 顼 | ϤäפǤ衼
	| ͥ | ʸʸϡġġ
	+------------+
	ʸʸϡĤä

	+------------+
	| Ч   | ϤäȤäפ
	| ͥ | 衼ʸʸϡġġ
	+------------+
	ʸʸϡĤä¿!

  ߤˤʤޤ򤱥եȤѤʤ顢mkdiary.rb Ʊǥ
  ȥ diary.css äơ

	img.thumnail {float: right;}

  ʤɤȽ񤭤ޤ礦rightʤ鱦򤱤Ǥ


  ȡźդ٤imgѤȤ! äƤȤϡ

	%IMGS
  ޤ
	%IMG*

  ɤ⡢ǥ쥯ȥŸ줿եƤ
  imgѤ롣%IMGSξϡimg<br>Ƕڤä
  󤹤ΤGUIʥ֥饦ǸȤ˰˲ԤƲ¤֡
  %IMG* ξϳimg򤽤Τޤ¤٤Τǡ¤֡
  ۤ

¾

  ȡɤǤ⤨󤸤㤱ɡ֤㤢%IMGΤΤ񤭤
  Ϥɤ?פäƵ䤬Ф롣ꤸ͡ʤؤ
  ݤե륿ץǡפʤפȻפɡ⤷
  "%IMG" ΤΤ줿 "%%IMG" %ĽŤͤƤ٤
  Ǥ⤨͡

=end


if ENV["img_n"] && (n=ENV["img_n"].to_i) > 0 then
  $imgfiles=(1..n).collect{|i| ENV["img_#{i}"]}
else
  $imgfiles = Dir.glob("*.{[Jj][Pp][Gg],[Pp][Nn][Gg]}")
end
@autorot=false
`which mogrify` > '' && @autorot=true

def charAt(handle, at)
  handle.seek(at, 0)
  return handle.read(1)[0]
end

def jpgsize(file)
  filesize=File.size(file)
  return nil if filesize < 2	# must have jpeg id (2bytes) at least
  open(file, "r"){|h|
    buf = h.read(2)
    comment=""
    return nil if buf[0] != 0xff || buf[1] != 0xd8
    seekpoint = 2
    catch (:exit) {
      while seekpoint < filesize-4
	if charAt(h, seekpoint) != 0xff then
	  throw :exit, 0
	elsif [192, 198, 194, 195, 197, 198, 199,
	    201, 202, 203, 205, 206, 207].index(charAt(h, 1+seekpoint)) then
	  # jpeg geometry area found!
	  h.seek(5+seekpoint, 0)
	  buf = h.read(4)
	  x = buf[2..3].unpack("n")[0]
	  y = buf[0..1].unpack("n")[0]
	  throw :exit, [x, y, comment]
	elsif 0xFE == charAt(h, 1+seekpoint) then
	  # JPEG comment area
	  h.seek(2+seekpoint, 0)
	  len = h.read(2).unpack("n")[0]
	  comment << h.read(len-2)+" "
	else
	  # Other marker
	  # Do nothing
	end
	seekpoint += 2
	h.seek(seekpoint, 0)
	buf = h.read(2)
	seekpoint += buf.unpack("n")[0]
      end
    }
  }
end

def pngsize(file)
  filesize=File.size(file)
  return if filesize < 0x18
  open(file, "r"){|h|
    buf = h.read(0x18)
    return nil if buf[0] != 0x89 || buf[1..3] != "PNG"
    x = buf[16..19].unpack("N")[0]
    y = buf[20..23].unpack("N")[0]
    return x, y
  }
end

def imgsrc(str)
  return "%" if str == "%%"	# %% escape
  if str == "%%" then
    return "%"
  elsif /IMG([S*])/ =~ str then
    sep = ($1 == "S") ? "<br>\n" : "\n"
    (0..$imgfiles.length-1).collect{|n|
      imgsrc("%IMG#{n}") + sep
    }.join('')
  elsif /IMG([0-9]+)(=(.*))?/ =~ str then
    cmt = $3
    n = if $1 > "" then $1.to_i - 1 else 0 end
    fn = $imgfiles[n]
    system("mogrify -auto-orient '#{fn}'") if @autorot
    if cmt && fn  then		# img2www mode
      require 'kconv'
      ENV['OUTCODE'].is_a?(String) and
        /jis/ =~ ENV['OUTCODE'] and cmt = cmt.tojis
      img2www = ENV["opt_img2www"] || "img2www"
      varname="cmt"+fn.sub(/\..*/, "").gsub("-", "_")
      ENV[varname] = cmt
      sprintf("%s", `#{img2www} -na -batch #{fn}`)
    else
      alt = ''
      if /png$/i =~ fn then
	xy = pngsize(fn)
      elsif /jpg$/i =~ fn then
	xy = jpgsize(fn)
	alt = xy[2]
      end
      if xy then
	sprintf("<img src=\"%s\" alt=\"%s\" width=\"%d\" height=\"%d\">",
		fn, (alt > "") ? alt : "photo", xy[0], xy[1])
      else
	sprintf("<img src=\"%s\" alt=\"photo\">", fn)
      end
    end
  end
end



while line=gets
  line.gsub!(/%%|%IMG[0-9S*]+(=.*)?/){|s|imgsrc(s)}
  print line
end
