#!/usr/bin/env ruby

# For security reasons, ensure that '.' is not on the load path
# This is primarily for 1.8.7 since 1.9.2+ doesn't put '.' on the load path
$LOAD_PATH.delete '.'

require 'mcollective'
require 'mcollective/runner'
require 'getoptlong'

opts = GetoptLong.new(
  [ '--daemonize', GetoptLong::NO_ARGUMENT],
  [ '--no-daemonize', GetoptLong::NO_ARGUMENT],
  [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
  [ '--config', '-c', GetoptLong::REQUIRED_ARGUMENT],
  [ '--pidfile', '-p', GetoptLong::REQUIRED_ARGUMENT]
)

daemonize = nil

if MCollective::Util.windows?
  configfile = File.join(MCollective::Util.windows_prefix, "etc", "server.cfg")
else
  # search for the server.cfg in the AIO path then the traditional one
  configfiles = ['/etc/puppetlabs/mcollective/server.cfg',
                 '/etc/mcollective/server.cfg' ]

  found = configfiles.find_index { |file| File.readable?(file) }

  # didn't find any? default to the first
  if found.nil?
    found = 0
  end

  configfile = configfiles[found]
end
pid = ""

opts.each do |opt, arg|
  case opt
    when '--help'
      puts "Usage: mcollectived.rb [--config /path/to/config] [--pidfile /path/to/pid] [--daemonize | --no-daemonize]"
      exit
    when '--config'
      configfile = arg
    when '--pidfile'
      pid = arg
    when '--daemonize'
      daemonize = true
    when '--no-daemonize'
      daemonize = false
  end
end

config = MCollective::Config.instance

config.loadconfig(configfile) unless config.configured

# If daemonize has not been set on the cli, reach into the config file to decide
if daemonize == nil
  daemonize = config.daemonize
end

MCollective::Log.info("The Marionette Collective #{MCollective::VERSION} started logging at #{config.loglevel} level")

if daemonize
  MCollective::Log.debug("Starting in the background (#{config.daemonize})")

  if MCollective::Util.windows?
    require 'mcollective/windows_daemon'
    MCollective::WindowsDaemon.daemonize_runner
  else
    require 'mcollective/unix_daemon'
    MCollective::UnixDaemon.daemonize_runner(pid)
  end
else
  MCollective::Log.debug("Starting in the foreground")
  runner = MCollective::Runner.new(configfile)
  runner.main_loop
end
