#!/usr/bin/env ruby
#  Phusion Passenger - http://www.modrails.com/
#  Copyright (C) 2008  Phusion
#
#  Phusion Passenger is a trademark of Hongli Lai & Ninh Bui.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; version 2 of the License.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

root = File.expand_path("#{File.dirname(__FILE__)}/..")
$LOAD_PATH.unshift("#{root}/lib", "#{root}/ext")
DEFAULT_INPUT_FD = 3

begin
	STDOUT.sync = true
	STDERR.sync = true
	$0 = "Passenger spawn server"
	if GC.respond_to?(:copy_on_write_friendly=)
		GC.copy_on_write_friendly = true
	end
	
	input = IO.new(DEFAULT_INPUT_FD)
	# Optimization for decreasing startup time. Since Apache starts the spawn
	# server twice during startup, we don't want to load the Passenger classes
	# if we don't need them.
	# So we check whether Apache immediately closes the connection. If so,
	# we exit without loading the rest of Passenger. If Apache doesn't close
	# the connection within 4 seconds then we continue with loading Passenger,
	# so that loading doesn't happen during the first spawn.
	if select([input], nil, nil, 4) && input.eof?
		exit
	end
	
	require 'passenger/spawn_manager'
	spawn_manager = Passenger::SpawnManager.new
	spawn_manager.start_synchronously(input)
	spawn_manager.cleanup
rescue => e
	require 'passenger/utils'
	include Passenger::Utils
	print_exception("spawn manager", e)
	exit 10
end
