require 'optparse'
require 'fileutils'
require 'tmpdir'
OPTIONS = {
:port => 3000,
:ip => "0.0.0.0",
:daemon => false,
:environment => "development",
:app_name => Process::pid.to_s,
:max_procs => 3,
:min_procs => 1,
:ssl => false,
:pemfile => "server.pem",
}
ARGV.options do |opts|
script_name = File.basename($0)
opts.banner = "Usage: ruby #{script_name} [options]"
opts.separator ""
opts.on("-p", "--port=port", Integer,
"Runs Rails on the specified port.",
"Default: 8000") { |OPTIONS[:port]| }
opts.on("-b", "--binding=ip", String,
"Binds Rails to the specified ip.",
"Default: 0.0.0.0") { |OPTIONS[:ip]| }
opts.on("-e", "--environment=name", String,
"Specifies the environment to run this server under (test/development/production).",
"Default: development") { |OPTIONS[:environment]| }
opts.on("-a", "--app-name=name", String,
"Specifies the application name.",
"Default: process_id") { |OPTIONS[:app_name]| }
opts.on("-d", "--daemon",
"Make lighttpd / Rails run as a Daemon (only works if fork is available -- meaning on *nix)."
) { OPTIONS[:daemon] = true }
opts.on("-n", "--min-procs=number", Integer,
"Minimum number of FastCGI processes allowed.",
"Default: 1") { |OPTIONS[:min_procs]| }
opts.on("-m", "--max-procs=number", Integer,
"Maximum number of FastCGI processes allowed.",
"Default: 3") { |OPTIONS[:max_procs]| }
opts.on("-l", "--enable-ssl",
"Enable SSL."
) { OPTIONS[:ssl] = true }
opts.on("-f", "--pemfile=pemfile", String,
"path to the PEM file for SSL support."
) { |OPTIONS[:pemfile]| }
opts.separator ""
opts.on("-h", "--help",
"Show this help message.") { puts opts; exit }
opts.parse!
end
ENV["RAILS_ENV"] = OPTIONS[:environment]
RAILS_ROOT = Dir.pwd + "/./"
TMP_DIR = Dir.tmpdir
LIGHTTPD_CONF_FILE = TMP_DIR + "/lighttpd.#{OPTIONS[:app_name]}.conf"
conf = DATA.read
conf.gsub!('__PORT__', OPTIONS[:port].to_s)
conf.gsub!('__BINDING__', OPTIONS[:ip])
conf.gsub!('__RAILS_ROOT__', File.expand_path(RAILS_ROOT))
conf.gsub!('__APP_NAME__', OPTIONS[:app_name])
conf.gsub!('__MIN_PROCS__', OPTIONS[:min_procs].to_s)
conf.gsub!('__MAX_PROCS__', OPTIONS[:max_procs].to_s)
conf.gsub!('__RAILS_ENV__', ENV['RAILS_ENV'])
conf.gsub!('__TMP_DIR__', TMP_DIR)
conf.gsub!('__SSL__', OPTIONS[:ssl] ? "enable" : "disable")
conf.gsub!('__PEMFILE__', OPTIONS[:pemfile])
File.open(LIGHTTPD_CONF_FILE, "w") { |output| output.write(conf) }
CMD = "/usr/sbin/lighttpd -f #{LIGHTTPD_CONF_FILE}"
CMD << " -D" if not OPTIONS[:daemon]
puts "=> Rails application started on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
puts "=> Ctrl-C to shutdown server; call with --help for options" if not OPTIONS[:daemon]
puts CMD
`
FileUtils.rm Dir.glob(TMP_DIR + "/lighttpd.#{OPTIONS[:app_name]}.*") if not OPTIONS[:daemon]