#!/usr/bin/env oo-ruby
require 'getoptlong'

def quarantine_action(quarantine=true)
  begin
    db = OpenShift::DataStore.db(:primary)

    # Mark all the gears as an update in progress
    gear_count = 0
    gear_search_count = 1
    while gear_search_count > 0
      filter = {"gears.#{gear_count}" => {"$exists" => true}}
      update_query = {'$set' => {"gears.#{gear_count}.quarantined" => quarantine}}
      db["applications"].update(filter, update_query, { :multi => true })
      gear_count += 1
      gear_search_count = db["applications"].find({"gears.#{gear_count}" => {"$exists" => true}}).count
    end
  rescue Exception => e
    puts e.message
    puts e.backtrace
    exit 1
  end
end

def p_usage
  puts <<USAGE
== Synopsis

#{File.basename $0}: An administrator utility to quarantine gears while a system upgrade is in process.

== Usage

#{File.basename $0}: OPTIONS

  --quarantine-all                     Quarantine all gears
  --unquarantine-all                   Unquarantine all gears
  --help                               Show usage info

USAGE
  exit 255
end

begin
  opts = GetoptLong.new(
    ["--quarantine-all", "-q", GetoptLong::NO_ARGUMENT],
    ["--unquarantine-all", "-u", GetoptLong::NO_ARGUMENT],
    ["--help", "-h", GetoptLong::NO_ARGUMENT]
  )
  opt = {}
  opts.each do |o, a|
    opt[o[2..-1]] = a.to_s
  end
rescue Exception => e
  p_usage
end

if opt['help']
  p_usage
end

$:.unshift('/var/www/openshift/broker')
require 'config/environment'

if opt['quarantine-all']
  quarantine_action
elsif opt['unquarantine-all']
  quarantine_action(false)
else
  puts "quarantine-all or unquarantine-all is required!"
  p_usage
end

puts "Done!"
