#!/usr/bin/ruby
# -*- coding: utf-8 -*-

# Copyright (C) 2008, IWAMURO Motonori
# All rights reserved.
#
# License: BSD License (revised)
# see http://vmi.jp/software/ruby/COPYING

require 'fileutils'

include FileUtils
include FileTest

outdir = "."
opencmd = nil

if opencmd.nil?
  case RUBY_PLATFORM
  when /cygwin/
    opencmd = 'cygstart'
  end
end

if ARGV.length == 0
  puts <<-HELP
* Bookmarklet Maker:
  Convert JavaScript file to HTML file with bookmarklet.

  Usage: #{$0} JS_FILE
  HELP
  exit 1
end

if !directory?(outdir)
  mkpath(outdir)
  $stderr.puts "Info: Directory [#{outdir}] created."
end
if %r@/$@ !~ outdir
  outdir += '/'
end

ifile = ARGV.shift
name = ifile.sub(%r{^.*[/\\]}, '').sub(%r{\.js$}, '')
ofile = outdir + name + ".html"

# マクロ定義
map = Hash.new
ARGV.each { |e|
  key, value = e.split(/\=/, 2)
  map[key] = value
}

js = IO.read(ifile)
js.gsub!(/\"/, "'")

# マクロ置換
js.gsub!(/\#\{(\w+)\}/) {
  key = $1
  if value = map[key]
    # value is not nil
    $stderr.puts "Replace: #{key} -> #{value}"
    value
  else
    # nil
    $stderr.puts "Missing definition of #{key}"
    exit 1
  end
}

# 空行／コメント行を削除
js.gsub!(%r{^//.*$|\s+(?://.*)?$}, '')
# 範囲コメントを削除
js.gsub!(%r{/\*.*?\*/}m, '')
# 先頭／末尾の空白を削除
js.gsub!(%r{\A\s+|/\*.*?\*/|\s+\z}m, '')
#js.gsub!(%r{\s*(\W)\s*}, '\1')
# 空白列を圧縮
js.gsub!(%r{\s+}m, ' ')
bmlet = "javascript:void(function(){#{js}}())"

open(ofile, 'w') {|wfh|
  wfh.puts <<-HTML
<html>
<head>
<title>#{name}</title>
</head>
<body>
Bookmarklet: <a href="#{bmlet}" alt="#{name}">#{name}</a><br>
<textarea rows="16" cols="80">
#{bmlet}
</textarea>
</body>
</html>
  HTML
}

$stderr.print "#{ofile} created."
if opencmd
  $stderr.print(" Opening it...")
  system(opencmd, ofile)
end
$stderr.puts

