#!/usr/bin/env ruby
#  Phusion Passenger - http://www.modrails.com/
#  Copyright (c) 2008, 2009 Phusion
#
#  "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.

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.
	begin
		if select([input], nil, nil, 4) && input.eof?
			exit
		end
	rescue Interrupt
		exit
	end
	
	require 'phusion_passenger/utils'
	if defined?(PhusionPassenger::NativeSupport)
		PhusionPassenger::NativeSupport.disable_stdio_buffering
	end
	PhusionPassenger::Utils.passenger_tmpdir = ARGV[0]
	
	require 'phusion_passenger/spawn_manager'
	spawn_manager = PhusionPassenger::SpawnManager.new
	spawn_manager.start_synchronously(input)
	spawn_manager.cleanup
rescue => e
	require 'phusion_passenger/utils'
	include PhusionPassenger::Utils
	print_exception("spawn manager", e)
	exit 10
end
