# Set environment to development unless something else is specified
env = "staging"
app_name = "joegattnet_v3_staging"

# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete
# documentation.
worker_processes 4

# Preload our app for more speed
preload_app true

# nuke workers after 15 seconds instead of 60 seconds (the default)
timeout 15

app_path = "/home/deployer/apps/#{ app_name }"

pid "#{ app_path }/current/tmp/pids/unicorn.pid"

# listen on both a Unix domain socket and a TCP port,
# we use a shorter backlog for quicker failover when busy
listen "/tmp/#{ app_name }.socket", :backlog => 64

# feel free to point this anywhere accessible on the filesystem
user 'deployer', 'staff'

# Help ensure your application will always spawn in the symlinked
# "current" directory that Capistrano sets up.
working_directory "#{ app_path }/current"

stderr_path "#{ app_path }/shared/log/unicorn.stderr.log"
stdout_path "#{ app_path }/shared/log/unicorn.stdout.log"

ENV['BUNDLE_GEMFILE'] = "#{ app_path }/current/Gemfile"

before_fork do |server, worker|
  # the following is highly recomended for Rails + "preload_app true"
  # as there's no need for the master process to hold a connection
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.connection.disconnect!
  end

  # Before forking, kill the master process that belongs to the .oldbin PID.
  # This enables 0 downtime deploys.
  old_pid = "#{ server.config[:pid] }.oldbin"

  if File.exists?(old_pid) && server.pid != old_pid
    begin
      Process.kill("QUIT", File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
      # someone else did our job for us
    end
  end
end

after_fork do |server, worker|
  # the following is *required* for Rails + "preload_app true",
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection
  end

  # if preload_app is true, then you may also want to check and
  # restart any other shared sockets/descriptors such as Memcached,
  # and Redis.  TokyoCabinet file handles are safe to reuse
  # between any number of forked children (assuming your kernel
  # correctly implements pread()/pwrite() system calls)
end
