use exit! for fun and profit
[god.git] / bin / god
blob9488da637c5e9071d5f4143478fbd862bd496b9d
1 #!/usr/bin/env ruby
3 $:.unshift File.join(File.dirname(__FILE__), *%w[.. lib])
5 require 'rubygems'
6 require 'optparse'
7 require 'drb'
9 require 'daemons'
10 require 'god'
12 options = {:daemonize => true, :port => 17165}
14 OptionParser.new do |opts|
15 opts.banner = <<-EOF
16 Usage: god [command] [options]
18 Commands:
19 start <watch or group name>
20 stop <watch or group name>
21 monitor <watch or group name>
22 unmonitor <watch or group name>
24 Options:
25 EOF
27 opts.on("-cCONFIG", "--config-file CONFIG", "Configuration file") do |x|
28 options[:config] = x
29 end
31 opts.on("-pPORT", "--port PORT", "Communications port") do |x|
32 options[:port] = x
33 end
35 opts.on("-D", "--no-daemonize", "Don't daemonize") do
36 options[:daemonize] = false
37 end
39 opts.on("-v", "--version", "Print the version number and exit") do
40 options[:version] = true
41 end
42 end.parse!
44 if options[:version]
45 # print version
46 puts "Version #{God::VERSION}"
47 exit!
48 elsif command = ARGV[0]
49 # a command was specified
51 # disable at_exit
52 # module God; def self.at_exit; end; end
54 # get the name of the watch/group
55 name = ARGV[1]
57 # connect to remote drb
58 DRb.start_service
59 server = DRbObject.new nil, "druby://localhost:#{options[:port]}"
61 begin
62 puts "Sending '#{command}' command"
64 # send command
65 watches = server.control(name, command)
67 # output response
68 puts 'The following watches were affected:'
69 watches.each do |w|
70 puts ' ' + w.name
71 end
72 rescue God::InvalidCommandError
73 abort "Command '#{command}' is not valid. Run 'god --help' for usage"
74 end
76 exit!
77 else
78 # start god
79 if !options[:daemonize]
80 load File.expand_path(options[:config])
81 else
82 pid = fork do
83 begin
84 # Dir.chdir "/"
85 STDIN.reopen "/dev/null"
86 STDOUT.reopen('god.log', "a")
87 STDERR.reopen STDOUT
89 puts "Starting god"
91 unless God::EventHandler.loaded?
92 puts
93 puts "***********************************************************************"
94 puts "*"
95 puts "* Event conditions are not available for your installation of god."
96 puts "* You may still use and write custom conditions using the poll system"
97 puts "*"
98 puts "***********************************************************************"
99 puts
102 puts "Resetting file descriptors"
104 # Daemons.daemonize if options[:daemonize]
106 puts "Loading config"
108 load File.expand_path(options[:config])
109 rescue => e
110 File.open('god.log', 'a') { |f| f.puts e.message + "\n" + e.backtrace }
111 abort "!!! ERROR !!!"
115 File.open("god.pid", 'w') { |f| f.write pid }
117 ::Process.detach pid
119 # disable at_exit
120 module God; def self.at_exit; end; end