# TODO: Still work in progress; must be tested in an AWS environment
# To test from the box, run:
#
# export PATH=$PATH:/opt/chef/embedded/bin/
#
# /opt/chef/embedded/lib/ruby/gems/2.1.0/gems/ohai-8.1.1/bin/ohai \
#  customdata -d /etc/chef/ohai_plugins/ -l debug
#
require 'json'

# Encoding: utf-8
Ohai.plugin(:Ec2Data) do
  depends 'ec2'
  depends 'customdata'

  provides 'customdata/peer_nodes', 'customdata/node_count', 'customdata/sg_peer_nodes', 'customdata/tags'

  def aws_nodes
    aws_nodes_path = '/etc/ohai-data/aws_nodes.json'

    if File.file?(aws_nodes_path)
      # TODO: find alternative, or drop list_instances.py in /usr_local_bin of img-basic
      # ec2 plugin should already have all data needed
      # if Time.now.to_i -  File.stat('/tmp/aws_nodes.json').mtime.to_i > 40
      #   `python /usr/local/bin/list_instances.py > /tmp/aws_nodes.json`
      # end
      jsonfile = open(aws_nodes_path).read
      json = JSON.load(jsonfile)
      return json
    end
  end

  collect_data do
    data = get_data_from_file('/etc/ohai-data/userdata')
    env = data['env']

    nodes = aws_nodes

    regexp_to_peers = [
      { regexp => /^Trans$/, env => 'PROD', peer => 'trans' },
      { regexp => /^Solr$/, env => 'PROD', peer => 'solr' },
      { regexp => /^Internet$/, env => 'PROD', peer => 'web' },
      { regexp => /^Alfresco$/, env => 'PROD', peer => 'alfresco' },
      { regexp => /^STAG-sgTrans$/, env => 'STAG', peer => 'trans' },
      { regexp => /^STAG-sgSolr$/, env => 'STAG', peer => 'solr' },
      { regexp => /^STAG-sgInternet-/, env => 'STAG', peer => 'web' },
      { regexp => /^STAG-sgAlfresco-/, env => 'STAG', peer => 'alfresco' },
      { regexp => /^DR-TRANS-/, env => 'DR', peer => 'trans' },
      { regexp => /^DR-SOLR-/, env => 'DR', peer => 'solr' },
      { regexp => /^DR-WEB-/, env => 'DR', peer => 'web' },
      { regexp => /^DR-ALFRESCO-/, env => 'DR', peer => 'alfresco' },
      { regexp => /^-TRANS-/, peer => 'trans' },
      { regexp => /^-SOLR-/, peer => 'solr' },
      { regexp => /^-WEB-/, peer => 'web' },
      { regexp => /^-ALFRESCO-/, peer => 'alfresco' }
    ]

    # Creating peer_nodes
    if nodes
      customdata['node_count'] = Mash.new
      customdata['sg_peer_nodes'] = Mash.new
      customdata['peer_nodes'] = {}
      customdata['tags'] = Mash.new

      nodes.each do |node|
        name = node['tags']['Name'].downcase
        private_address = node['private_ip_address']

        regexp_to_peers.each do |regexp_to_peer|
          next unless regexp_to_peer['regexp'] =~ group
          peer = regexp_to_peer['peer']
          customdata['peer_nodes'][peer] = {} unless customdata['peer_nodes'][peer]
          customdata['peer_nodes'][peer][name] = private_address
        end
      end

      %w(alfresco solr trans web).each do |type|
        if customdata['node_count'][type]
          customdata['node_count'][type] = customdata['peer_nodes'][type].count
        end
      end

      if ec2 && ec2['security_groups']
        ec2['security_groups'].each do |sg|
          nodes.each do |node|
            if node['groups'].include? sg
              name = node['tags']['Name'].downcase
              customdata['sg_peer_nodes'][name] = node['private_ip_address']
            end
          end
        end
      end

      if looks_like_ec2?
        instance_id = open('http://169.254.169.254/latest/meta-data/instance-id').read

        nodes.each do |node|
          customdata['tags'] = node['tags'] if instance_id == node['id']
        end
      end
    else
      Ohai::Log.debug('No nodes found; check /etc/ohai-data/aws_nodes.json')
      false
    end
  end
end
