#!/opt/chef-backend/embedded/bin/ruby
UNICAST_CONFIG_KEY = "discovery.zen.ping.unicast.hosts".freeze

def fix_unicast_host_config
  current_members = LibCB::Cluster.peers
  current_configured_members = current_config[UNICAST_CONFIG_KEY]
  puts "   Current peer list: #{current_members}"
  puts "Configured peer list: #{current_configured_members}"
  if current_configured_members.sort != current_members.sort
    puts "Peer list differs, rewriting configuration."
    # Don't reduce the member list as a result of a rewrite here This
    # script is to help ensure ES is safe to restart.  If an Etcd
    # issue means we are getting a new shorter member_list, we don't
    # want to prevent ES from coming online properly anyway.
    new_member_list = (current_members + current_configured_members).uniq.sort
    rewrite_config(new_member_list)
    puts "Configuration rewritten."
  else
    puts "Peer list correct, continuing with ES startup."
  end
end

def config_file_path
  @config_path ||= File.join(LibCB.node['chef-backend']['elasticsearch']['dir'], "config", "elasticsearch.yml")
end

def current_config
  @current_config ||= YAML.load(current_config_file_content)
end

def current_config_file_content
  @current_content ||= File.read(config_file_path)
end

def new_unicast_line(new_member_list)
  "#{UNICAST_CONFIG_KEY}: #{new_member_list.to_s}\n"
end

def owner
  LibCB.node['chef-backend']['user']['username']
end

def rewrite_config(new_member_list)
  temp_file = Tempfile.new("new_config", nil)
  begin
    current_config_file_content.lines.each do |line|
      if line =~ /^#{UNICAST_CONFIG_KEY}:/
        temp_file.write(new_unicast_line(new_member_list))
      else
        temp_file.write(line)
      end
    end
    # Fix pemrissions before moving the file into place
    # mv should preserve permissions
    FileUtils.chown(owner, owner, temp_file.path)
    FileUtils.chmod(0644, temp_file.path)
    temp_file.fsync
    FileUtils.mv(temp_file.path, config_file_path)
  ensure
    temp_file.close
    temp_file.unlink
  end
end

begin
  puts "ElasticSearch pre-start script started."
  require 'libcb'
  require 'yaml'
  require 'libcb/cluster'
  require 'tempfile'
  require 'fileutils'
  LibCB.load
  fix_unicast_host_config
# This script runs as part of the ES init script.  We don't
# want to always exit 0 to avoid preventing an ES startup.
rescue Exception => e
  puts "Failed to fix unicast host config: #{e}"
  puts "Exiting cleanly anyway to allow runit to continue."
  exit(0)
end
puts "ElasticSearch pre-start script completed."
exit(0)
