8b24892666d96f3d884e8b247911c01cbb91209d
[packages/precise/mcollective.git] / ext / windows / service_manager.rb
1 require 'optparse'
2
3 opt = OptionParser.new
4
5 ruby_path = ENV["RUBY"].gsub('"','')
6 basedir = ENV["BASEDIR"]
7 libdir = ENV["RUBYLIB"]
8 mcollectived = ENV["MCOLLECTIVED"]
9 configfile = ENV["SERVER_CONFIG"]
10
11 unless File.exist?(ruby_path)
12   ENV["PATH"].split(File::PATH_SEPARATOR).each do |path|
13     ruby = File.join(path, "ruby.exe")
14
15     if File.exist?(ruby)
16       ruby_path = ruby
17       break
18     end
19   end
20 end
21
22 abort("Can't find ruby.ext in the path") unless ruby_path
23
24 options = {:name    => "mcollectived",
25            :display_name => "The Marionette Collective",
26            :description => "Puppet Labs server orchestration framework",
27            :command => '%s -I"%s" -- "%s" --config "%s"' % [ ruby_path, libdir, mcollectived, configfile ]}
28
29 action = false
30
31 opt.on("--install", "Install service") do
32   action = :install
33 end
34
35 opt.on("--uninstall", "Remove service") do
36   action = :uninstall
37 end
38
39 opt.on("--name NAME", String, "Service name (#{options[:name]})") do |n|
40   options[:name] = n
41 end
42
43 opt.on("--description DESCRIPTION", String, "Service description (#{options[:description]})") do |v|
44   options[:description] = v
45 end
46
47 opt.on("--display NAME", String, "Service display name (#{options[:display_name]})") do |n|
48   options[:display_name] = n
49 end
50
51 opt.on("--command COMMAND", String, "Service command (#{options[:command]})") do |c|
52   options[:command] = c
53 end
54
55 opt.parse!
56
57 abort "Please choose an action with --install or --uninstall" unless action
58
59 require 'rubygems'
60 require 'win32/service'
61
62 include Win32
63
64 case action
65   when :install
66     if ENV["MC_STARTTYPE"] =~ /auto/i
67       start_type = Service::AUTO_START
68     else
69       start_type = Service::DEMAND_START
70     end
71
72     Service.new(
73       :service_name => options[:name],
74       :display_name => options[:display_name],
75       :description => options[:description],
76       :binary_path_name => options[:command],
77       :service_type => Service::SERVICE_WIN32_OWN_PROCESS,
78       :start_type => start_type
79     )
80
81     puts "Service %s installed" % [options[:name]]
82
83   when :uninstall
84     Service.stop(options[:name]) unless Service.status(options[:name]).current_state == 'stopped'
85
86     while Service.status(options[:name]).current_state != 'stopped'
87       puts "Waiting for service %s to stop" % [options[:name]]
88       sleep 1
89     end
90
91     Service.delete(options[:name])
92
93     puts "Service %s removed" % [options[:name]]
94 end