#!/usr/bin/env ruby
#
#  Created on 2008-3-11.
#  Copyright (c) 2008. All rights reserved.

begin
  require 'rubygems'
rescue LoadError
  # no rubygems to load, so we fail silently
end

require 'optparse'

# NOTE: the option -p/--path= is given as an example, and should probably be replaced in your application.

OPTIONS = {}
MANDATORY_OPTIONS = %w( path )

ARGV.each do |arg|
  ENV[$1] = $2 if arg =~ /^(\w+)=(.*)$/
end

parser = OptionParser.new do |opts|
  opts.banner = <<BANNER
Sprinkle
========

http://github.com/crafterm/sprinkle

Sprinkle is a software provisioning tool you can use to build remote servers with. eg. to
install a Rails or Merb stack on a brand new slice directly after its been created. It uses
a Ruby based domain specific language to describe packages and policies to determine what
should be installed on particular systems.

Please see http://github.com/crafterm/sprinkle/tree/master/README.txt for more information.

Usage
=====

$> #{File.basename($0)} [options]

Options are:
BANNER
  opts.separator ""
  opts.on("-s", "--script=PATH", String,
          "Path to a sprinkle script to run") { |OPTIONS[:path]| }
  opts.on("-t", "--test",
          "Process but don't perform any actions") { |OPTIONS[:testing]| }
  opts.on("-v", "--verbose",
          "Verbose output") { |OPTIONS[:verbose]| }
  opts.on("-c", "--cloud",
          "Show powder cloud, ie. package hierarchy and installation order") { |OPTIONS[:cloud]| }
  opts.on("-f", "--force",
          "Force installation of all packages even if it is detected that it has been previously installed") { |OPTIONS[:force]| }
  opts.on("-h", "--help",
          "Show this help message.") { puts opts; exit }
  opts.parse!(ARGV)

  if MANDATORY_OPTIONS && MANDATORY_OPTIONS.find { |option| OPTIONS[option.to_sym].nil? }
    puts opts; exit
  end
end

def force_mode(options)
  Sprinkle::OPTIONS[:force] = OPTIONS[:force] || false
end

def operation_mode(options)
  Sprinkle::OPTIONS[:testing] = OPTIONS[:testing] || false
end

def powder_cloud(options)
  Sprinkle::OPTIONS[:cloud] = OPTIONS[:cloud] || false
end

def log_level(options)
  Object.logger.level = ActiveSupport::BufferedLogger::Severity::DEBUG if options[:verbose]
end

require File.dirname(__FILE__) + '/../lib/sprinkle'

powder = OPTIONS[:path]
raise "Sprinkle script is not readable: #{powder}" unless File.readable?(powder)

force_mode(OPTIONS)
operation_mode(OPTIONS)
powder_cloud(OPTIONS)
log_level(OPTIONS)

Sprinkle::Script.sprinkle File.read(powder), powder