# This recipe aims to help discovery process in EC2; it runs AWS commandline
# to discovers other machines, depending on their tags and delivers a list
# of IPs/urls that are ready to be configured by client services
#
# AWS commandline tool is provided by artifact-deployer
#
query_tags = node['ec2']['query_tags']
peers_file_path = node['ec2']['peers_file_path']
aws_bin = node['ec2']['aws_bin']

# Query AWS instances and set node attributes for service discovery configuration
if query_tags
  query_tag_filter = ''
  query_tags.each do |tag_name, tag_value|
    query_tag_filter += "--filters Name=tag:#{tag_name},Values=#{tag_value} "
  end

  execute 'create-ec2-peers-json' do
    command "#{aws_bin} ec2 describe-instances #{query_tag_filter} > #{peers_file_path}"
    # re-create it every time
    # creates peers_file_path
  end

  ruby_block "handling-#{peers_file_path}" do
    block do
      file = File.read(peers_file_path)
      peers_hash = JSON.parse(file)
      if peers_hash['Reservations'] && !peers_hash['Reservations'].empty?
        peers_hash['Reservations'][0]['Instances'].each do |awsnode|
          private_ip = awsnode['PrivateIpAddress']
          status = awsnode['State']['Name']
          id = awsnode['InstanceId']
          next unless status == 'running'
          awsnode['Tags'].each do |tag|
            role = tag['Value']
            node.default['ec2']['query_results'][role][id] = private_ip
          end
        end
      end
    end
    action :run
  end
end
