#!/usr/bin/env ruby

require 'bosh/director/config'
require 'bosh/director/sync_dns_scheduler'
require 'bosh/director/agent_broadcaster'
require 'bosh/director/dns/dns_version_converger'

def stop(reason, dns_sync_broadcaster)
  Bosh::Director::Config.logger.error("Shutting down bosh-director-sync-dns: #{reason}")
  dns_sync_broadcaster.stop!
  EM.stop
end

config_file = nil

opts = OptionParser.new do |op|
  op.on('-c', '--config [ARG]', 'Configuration File') do |opt|
    config_file = opt
  end
end

opts.parse!(ARGV.dup)

config_file ||= ::File.expand_path('../../config/bosh-director.yml', __FILE__)
config = Bosh::Director::Config.load_file(config_file)

dns_sync_broadcaster = Bosh::Director::SyncDnsScheduler.new(config, 10)
dns_sync_broadcaster.prep

%w(TERM INT QUIT).each do |signal|
  trap(signal) do
    stop(signal, dns_sync_broadcaster)
  end
end


EventMachine.run do
  EM.defer do
    Thread.new do
      begin
        dns_sync_broadcaster.start!
      ensure
        stop('Thread terminated', dns_sync_broadcaster)
      end
    end
  end
end
