#! /usr/bin/env ruby
=begin
  rgettext.rb - Generate a .pot file.

  Copyright (C) 2003-2005  Masao Mutoh
  Copyright (C) 2001,2002  Yasushi Shoji, Masao Mutoh
 
      Yasushi Shoji   <yashi@yashi.com>
      Masao Mutoh     <mutoh@highway.ne.jp>
 
  You may redistribute it and/or modify it under the same
  license terms as Ruby.
=end

require 'optparse'
require 'gettext'

module GetText

  module RGetText
    extend GetText

    bindtextdomain("rgettext")

    # constant values
    VERSION = GetText::VERSION
    DATE = %w($Date: 2005/09/02 19:32:48 $)[1]
    MAX_LINE_LEN = 70

    EX_PARSERS = [
      ["glade.rb", "GladeParser"],
      ["erb.rb", "ErbParser"],
      ["ruby.rb", "RubyParser"] # Default parser.
    ]

    EX_PARSERS.each do |f, _|
      require File.join("gettext/parser/#{f}")
    end

    module_function

    def generate_pot_header
      time = Time.now.strftime("%Y-%m-%d %H:%M%z")
      %Q[# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\\n"
"POT-Creation-Date: #{time}\\n"
"PO-Revision-Date: #{time}\\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n"
"Language-Team: LANGUAGE <LL@li.org>\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n"]
    end

    def generate_pot(ary)
      str = ""
      result = Array.new
      ary.each do |key|
	msgid = key.shift
	curr_pos = MAX_LINE_LEN
	key.each do |e|
	  if curr_pos + e.size > MAX_LINE_LEN
	    str << "\n#:"
	    curr_pos = 3
	  else
	    curr_pos += (e.size + 1)
	  end
	  str << " " << e
	end
	msgid.gsub!(/"/, '\"')
	msgid.gsub!(/\r/, '')
	if msgid.include?("\000")
	  ids = msgid.split(/\000/)
	  str << "\nmsgid \"" << ids[0] << "\"\n"
	  str << "msgid_plural \"" << ids[1] << "\"\n"
	  str << "msgstr[0] \"\"\n"
	  str << "msgstr[1] \"\"\n"
	else
	  str << "\nmsgid \"" << msgid << "\"\n"
	  str << "msgstr \"\"\n"
	end
      end
      str
    end

    def parse(files)
      ary = []
      files.each do |file|
	begin
	  EX_PARSERS.each do |_, c|
	    klass = GetText.const_get(c)
	    if klass.target?(file)
	      ary = klass.parse(file, ary)
	      break
	    end
	  end
	rescue
	  puts $!
	  exit 1
	end
      end

      ary
    end

    def check_options
      output = STDOUT

      opts = OptionParser.new
      opts.banner = _("Usage: %s input.rb [-o output.pot]") % $0
      opts.separator("")
      opts.separator(_("Extract translatable strings from given input files."))
      opts.separator("")
      opts.separator(_("Specific options:"))

      opts.on("-o", "--output=FILE", _("write output to specified file")) do |out|
	unless FileTest.exist? out
	  output = File.new(File.expand_path(out), "w+")
	else
	  $stderr.puts(_("File '%s' has already existed.") % out)
	  exit 1
	end
      end

      opts.on_tail("--version", _("display version information and exit")) do
	puts "#{$0} #{VERSION} (#{DATE})"
	exit
      end

      opts.parse!(ARGV)

      if ARGV.size == 0
	puts opts.help
	exit 1
      end

      [ARGV, output]
    end

    def run(targetfiles = nil, out = STDOUT)
      if targetfiles.is_a? String
	targetfiles = [targetfiles]
      elsif ! targetfiles
	targetfiles, out = check_options
      end

      if targetfiles.size == 0
	raise ArgumentError, _("no input files")
      end

      if out.is_a? String
	File.open(File.expand_path(out), "w+") do |file|
	  file.puts generate_pot_header
	  file.puts generate_pot(parse(targetfiles))
	end
      else
	out.puts generate_pot_header
	out.puts generate_pot(parse(targetfiles))
      end

    end
  end

  module_function
  def rgettext(targetfiles = nil, out = STDOUT)
    RGetText.run(targetfiles, out)
  end
end

if $0 == __FILE__
  GetText.rgettext
#  GetText.rgettext($0, "tmp.txt")
end
