#!/usr/bin/env ruby
# Support frozen merb environment
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../framework/merb-core/lib"))
# Add backgroundrb folders to load path
backgroundrb_dir = Dir.glob(File.expand_path(File.dirname(__FILE__) + "/../gems/gems/backgroundrb_merb*")).last
["lib/backgroundrb_merb", "server/lib"].each { |x| $LOAD_PATH.unshift(backgroundrb_dir + "/#{x}")}
# Add workers to load path
WORKER_ROOT = File.expand_path(File.dirname(__FILE__) + "/../lib/workers")
$LOAD_PATH.unshift(WORKER_ROOT)
# Take preference to local merb gems
require "rubygems"
Gem.clear_paths
Gem.path.unshift(File.expand_path(File.dirname(__FILE__) + "/../gems"))
# Require dependencies
require 'merb-core'
require 'activerecord'
require "yaml"
require "erb"
require "logger"
require "packet"
require "bdrb_config.rb"
require "master_worker.rb"
# Parse CLI options
BackgrounDRbMerb::Config.parse_cmd_options ARGV
CONFIG_FILE = BackgrounDRbMerb::Config.read_config("#{Merb.root}/config/backgroundrb.yml")
pid_file = "#{Merb.root}/tmp/pids/backgroundrb_#{CONFIG_FILE[:backgroundrb][:port]}.pid"
SERVER_LOGGER = "#{Merb.root}/log/backgroundrb_server_#{CONFIG_FILE[:backgroundrb][:port]}.log"
case ARGV[0]
when 'start'
if fork
exit
else
op = File.open(pid_file, "w")
op.write(Process.pid().to_s)
op.close
if CONFIG_FILE[:backgroundrb][:log].nil? or CONFIG_FILE[:backgroundrb][:log] != 'foreground'
log_file = File.open(SERVER_LOGGER,"w+")
[STDIN, STDOUT, STDERR].each {|desc| desc.reopen(log_file)}
end
BackgrounDRbMerb::MasterProxy.new()
end
when 'stop'
pid = nil
File.open(pid_file, "r") { |pid_handle| pid = pid_handle.gets.strip.chomp.to_i }
begin
pgid = Process.getpgid(pid)
Process.kill('TERM', pid)
Process.kill('-TERM', pgid)
Process.kill('KILL', pid)
rescue Errno::ESRCH => e
puts "Deleting pid file"
rescue
puts $!
ensure
File.delete(pid_file) if File.exists?(pid_file)
end
else
BackgrounDRbMerb::MasterProxy.new()
end