#!/usr/bin/ruby

require 'nventory'
require 'time'
require 'optparse'

ETCH_SERVER_TZ = 'UTC'    # The etch servers run in UTC

options = {}
opts = OptionParser.new
opts.banner = 'Usage: etch_to_trunk [options] <server1> [<server2> <server3>]'
opts.on('-u', '--username USERNAME', 'Username for connecting to nventory server.') do |opt|
  options[:username] = opt
end 
opts.on('-t', '--timezone TIMEZONE', 'Time zone of etch server.') do |opt|
  options[:timezone] = opt
end 
opts.on('--nv SERVER', 'Where nVentory server is running.') do |opt|
  options[:nv_server] = opt
end
opts.on_tail('-h', '--help', 'Show this message.') do
  puts opts
  exit
end

nodes = opts.parse(ARGV)

if ARGV.length == 0
  puts opts
  exit
end

@username = options[:username] || ENV['LOGNAME']
etch_server_tz = options[:timezone] || ETCH_SERVER_TZ

if etch_server_tz
  currentheadtag = Time.at(Time.now.utc + Time.zone_offset(etch_server_tz)).strftime('trunk-%Y%m%d-%H00')
else  # if no timezone is specified then just use local time for the tag 
  currentheadtag = Time.now.strftime('trunk-%Y%m%d-%H00')
end

# Find the requested clients
nv_server = options[:nv_server]
if nv_server
  nvclient = NVentory::Client.new(:server=>"http://#{nv_server}")
else
  nvclient = NVentory::Client.new
end
results = nvclient.get_objects('nodes', {}, { 'name' => nodes }, {}, {})
nodes.each do |name|
  if results.empty? && results[name].nil?
    abort "No entry found for #{name}"
  else
    if !results[name]['config_mgmt_tag'].nil? &&
       !results[name]['config_mgmt_tag'].empty?
      puts "Changing #{name} from #{results[name]['config_mgmt_tag']} to #{currentheadtag}"
    else
      puts "Setting #{name} to #{currentheadtag}"
    end
  end
end

while true
  print "Proceed? [y|n] "
  response = $stdin.gets.chomp
  if response == 'y'
    break
  elsif response == 'n'
    exit
  end
end

# Update the clients
successcount = nvclient.set_objects('nodes', results, {'config_mgmt_tag' => currentheadtag}, @username)

puts "#{File.basename($0)} operation succeeded for #{successcount} of #{results.size} nodes"

