#!/usr/bin/ruby
#
# This script will start/stop/restart all mongrel clusters
# with parameters files stored in /etc/mongrel_cluster.
#
# This script will not start ou stop any mongrel cluster if
# the user is not defined inside config files, for security.
#
# It will also stop mongrels after sudo, because pid files
# are not secure (not owned by root).
#
# Tested with Ubuntu 6.06
#
# Script by Sam : http://blog-perso.onzeweb.info
#
# Thanks for that simple (but good) idea :
# http://www.rubyinside.com/how-to-create-a-unix-etcinitd-startup-script-with-ruby-250.html
#

require 'yaml'
require 'pathname'


# Change the path if you need

CHEMIN_CONFIGS = '/etc/mongrel_cluster'


# It's here all is done

def ExecuteSurTous(stop,start)
  Dir.chdir(CHEMIN_CONFIGS)
  Dir.glob('*.yml').each do |une_config|
    chemin_une_config=CHEMIN_CONFIGS+'/'+une_config
    begin
      utilisateur=YAML.load(File.new(chemin_une_config))['user']
    rescue
      utilisateur=nil
    end
    if not utilisateur
      STDERR.puts "User not defined in config : #{une_config}"
      return
    end
    STDOUT.puts "Using config file : #{une_config}"
    if stop
      system('sudo','-u',utilisateur,
             'mongrel_rails','cluster::stop','--config',chemin_une_config)
    end
    if start
      system('sudo','-u',utilisateur,
             'mongrel_rails','cluster::start','--config',chemin_une_config)
    end
  end
end


# It's here things begin

case ARGV.first
  when 'start':
    ExecuteSurTous(false,true)
  when 'stop':
    ExecuteSurTous(true,false)
  when 'restart':
    ExecuteSurTous(true,true)
end

unless %w{start stop restart}.include? ARGV.first
  puts "Usage: #{Pathname.new($0).basename} {start|stop|restart}"
  exit
end