#!/usr/bin/env ruby

require 'optparse'
require 'ostruct'
require 'yajl/json_gem'
require 'redis'

# add lib to the default include path
unless $:.include?(File.dirname(__FILE__) + '/../lib/')
  $: << File.dirname(__FILE__) + '/../lib'
end

require 'flapjack/configuration'
require 'flapjack/data/contact'
require 'flapjack/data/entity'
require 'flapjack/data/event'

options = OpenStruct.new
options.config    = File.join('etc', 'flapjack_config.yaml')
options.daemonize = nil

command = ARGV.shift

banner  = "Usage: flapjack-populator command [options]\n"
banner += "\n"
banner += "  commands:\n"
banner += "    - import-entities\n"
banner += "    - import-contacts\n"
banner += "    - purge-events (purge queued monitoring events)\n"

OptionParser.new do |opts|
  opts.banner = "Usage: flapjack-populator command [options]"

  opts.on("-c", "--config [PATH]", String, "PATH to the config file to use") do |c|
    options.config = c
  end

  opts.on("-f", "--from [FILE]", String, "path to the FILE to import") do |f|
    options.from = f
  end

end.parse!(ARGV)

FLAPJACK_ENV = ENV['FLAPJACK_ENV'] || 'development'

config = Flapjack::Configuration.new
config.load(options.config)
config_env = config.all
redis_options = config.for_redis

if config_env.nil? || config_env.empty?
  puts "No config data for environment '#{FLAPJACK_ENV}' found in '#{options.config}'"
  exit(false)
end

if options.from
  filename = options.from
  file     = File.new(filename)
end

case command
when "import-contacts"
  contacts = JSON.parse(file)

  if contacts && contacts.is_a?(Enumerable) && contacts.any? {|e| !e['id'].nil?}
    @persistence = Redis.new(redis_options)
    @persistence.multi do
      contacts.each do |contact|
        unless contact['id']
          puts "Contact not imported as it has no id: " + contact.inspect
          next
        end
        Flapjack::Data::Contact.add(contact, :redis => @persistence)
      end
    end
    @persistence.quit
  end

when "import-entities"
  entities = JSON.parse(file)

  if entities && entities.is_a?(Enumerable) && entities.any? {|e| !e['id'].nil?}
    @persistence = Redis.new(redis_options)
    @persistence.multi
    entities.each do |entity|
      unless entity['id']
        puts "Entity not imported as it has no id: " + entity.inspect
        next
      end
      Flapjack::Data::Entity.add(entity, :redis => @persistence)
    end
    @persistence.exec
    @persistence.quit
  end

when "purge-events"
  @persistence = Redis.new(redis_options)
  events_size = @persistence.llen('events')
  puts "purging #{events_size} events..."
  etq = "events.#{Time.now.to_i}"
  puts "renaming 'events' to '#{etq}'"
  @persistence.rename('events', etq)
  puts "setting expiry of '#{etq}' to 8 hours"
  @persistence.expire(etq, (60 * 60 * 8))
  @persistence.quit

else
  puts "you need to give me something to do, eg a command like 'import-entities' or 'import-clients' etc"
  raise ArgumentError
end