#!/usr/bin/env ruby

#
# $Id: pubtool.rb,v 1.1 2004/01/17 12:02:25 hn Exp $
# Copyright Narushima Hironori. All rights reserved.
#

dir = File.expand_path( File.dirname( __FILE__ ) + '/../lib')
if $CYGWIN = (/cygwin$/ === RUBY_PLATFORM)
	require (dir + '/cygpath.rb')
	dir = Cygwin::cygpath(dir)
end
$:.unshift(dir)

require 'getopts'
require 'webpub/eclipse_workspace'
require 'webpub/publish_manager'

usage = <<EOS
usage: wp [-pwc] files
  -h            show usage and ide extend options
  -p[directory or entry_file]
                eclipse based plug-in directories
  -w[directory] workspace directory
  -c[file]      plug-in location saved cache file
EOS

extend_usage = <<EOS
eclipse ide extend options:
  -t[file]      include publish files that entry separated by line feed code
  -s[file]      output result messages to file
  -e[file]      STDERR output to specify file
EOS

unless getopts('h', 'p:', 'w:', 'c:', 't:', 's:', 'e:')
	abort usage
end

if $OPT_h
	print usage, extend_usage
	exit
end

include Webpub

def find_workspace()
	dir = Dir.pwd
	begin
		return dir if File.directory?(dir + '/.metadata')
	end while dir.sub!(%r!/[^/]+?$!, '') and dir.count('/') > 0
	nil
end

begin
	$stdout = open($OPT_s, 'w') if $OPT_s
	$stderr = open($OPT_e, 'w') if $OPT_e
	
	if workspace_path = $OPT_w || ENV['ECLIPSE_WORKSPACE'] || find_workspace()
		EclipseWorkspace.instance.workspace_path = workspace_path
	else
		abort "workspace directory is not specified (use -w option or env ECLIPSE_WORKSPACE)"
	end
	
	pathes = $OPT_p || ENV['ECLIPSE_PLUGINS'] || File.expand_path( File.dirname(__FILE__) + '/../../..')
	pathes.split(File::PATH_SEPARATOR).each { |p|
		reg = PublisherRegistory.instance
		reg.collect_plugins(p)
	}
	
	mgr = PublishManager.new
	
	files = ARGV
	if $OPT_t
		files += IO.readlines($OPT_t).map { |f| f.strip }.select { |f| !f.empty? }
	end
	
	if files.empty?
		if File.exist?('.webproject')
			files = Dir.glob('**/*')
		else
			abort "not specified publish target file"
		end
	end

	mgr.publish(files)
	
rescue PublisherEnvironmentException
	abort $!.message
	
ensure
	$stdout.close if $OPT_s
	$stderr.close if $OPT_e
end
