#!/usr/bin/env ruby
#
# Samizdat dRuby object cache server
#
#   Copyright (c) 2002-2009  Dmitry Borodaenko <angdraug@debian.org>
#
#   This program is free software.
#   You can distribute/modify this program under the terms of
#   the GNU General Public License version 3 or later.
#
# vim: et sw=2 sts=2 ts=8 tw=0

require 'syslog'
require 'drb'
require 'samizdat/cache'

PNAME = 'samizdat-drb-server'
PIDFILE = (0 == Process.uid)? "/var/run/#{PNAME}.pid" :
  "#{ENV['TMPDIR']}/#{PNAME}.pid"

# daemonize
exit if fork
Process.setsid
exit if fork
Dir.chdir '/'
File.umask 0022
STDIN.reopen '/dev/null'
STDOUT.reopen '/dev/null', 'w'
STDERR.reopen STDOUT
$0 = PNAME
File.open(PIDFILE, 'w') {|f| f.puts Process.pid }
Process::Sys.setuid 65534 if 0 == Process.uid   # drop root priviledge

Syslog.open PNAME   # open syslog
cache = Samizdat::Cache.new(24*60*60, 10000, 5)   # initialize cache

# trap signals
shutdown = lambda do
  DRb.stop_service
  Syslog.info 'shut down'
end
Signal.trap('INT', shutdown)
Signal.trap('TERM', shutdown)
Signal.trap('HUP') do   # kill -HUP to flush cache
  cache.flush
  Syslog.info 'cache flushed'
end

# start service
$SAFE = 1
DRb.start_service((ARGV[0] or 'druby://localhost:9000'), cache)
Syslog.info 'started'

# wait for shut down
DRb.thread.join
File.delete PIDFILE   # fixme: can't remove it from /var/run once dropped root
