#!/usr/bin/env ruby

# in order to make cruise run as daemon, you need:
# 1. cp $CCRB_HOME/daemon/cruise.sample $CCRB_HOME/daemon/cruise
# 2. specify your cruise_path to $CCRB_HOME in $CCRB_HOME/daemon/cruise file
# 3. ln -s $CCRB_HOME/daemon/cruise /etc/init.d/cruise (you may need to 'sudo' this)
# 4. update-rc.d cruise (you may want to choose options by yourself, and you may need to 'sudo' this)
# 5. it's done :>

require "fileutils"
include FileUtils

require "rubygems"

begin
  gem 'mongrel'
rescue => e
  puts "Error: daemon mode of CC.rb requires mongrel installed"
  exit 1
end

def cruise_path
  # NOTE: you must specify $CCRB_HOME here
  # "/home/gigix/Projects/cc.rb"
  #raise "Please specify your $CCRB_HOME path in this method."
 '/home/foo/cruisecontrolrb-1.3.0'
end

def change_process_permissions_to desired_usr, desired_grp
  begin
    current_uid, current_gid = Process.euid, Process.egid
    target_uid, target_gid = Etc.getpwnam(desired_usr).uid, Etc.getgrnam(desired_grp).gid
    (current_uid == target_uid) && (current_gid == target_gid) && return
    Process.initgroups(desired_usr, target_gid)
    Process::GID.change_privilege(target_gid)
    print "Changed group to #{desired_grp}."
    Process::UID.change_privilege(target_uid)
    print "Changed user to #{desired_usr}."
    ENV['HOME'] = Etc.getpwuid(Process.euid).dir
  rescue Errno::EPERM
    $stderr.write "Cruise couldn't start: Failed to change user and group to #{desired_usr}:#{desired_grp} -> [#{$!.to_s}].\n"
    exit -1
  end
end

command = ARGV.shift

case command
when 'start'
  change_process_permissions_to 'foo', 'bar'
  cd cruise_path
  system "./cruise start -d"
  exit 0
when 'stop'
  system "mongrel_rails stop -P #{cruise_path}/tmp/pids/mongrel.pid"
  Dir["#{cruise_path}/tmp/pids/builders/*.pid"].each do |pid_file|
    pid = File.open(pid_file){|f| f.read }
    system "kill -9 #{pid}"
    rm pid_file
  end
  exit 0
else
  p "Usage: /etc/init.d/cruise start|stop"
  exit 1
end