conn = new Mongo();
db = conn.getDB("admin");
db.auth( '{{ MONGO_ADMIN_USER }}', '{{ MONGO_ADMIN_PASSWORD }}');

{# Generate a list of hosts if no cluster members are give. Otherwise use the
   hosts provided in the variable.
#}
{%- if mongo_cluster_members|length == 0 -%}
  {%- set hosts = [] -%}
  {%- set all_mongo_hosts = [] -%}
  {%- do all_mongo_hosts.extend(groups.tag_role_mongo) -%}
  {%- do all_mongo_hosts.extend(groups.tag_group_mongo) -%}
  {%- for name in  group_names -%}
    {%- if name.startswith(mongo_aws_stack_name) -%}
      {%- for host in all_mongo_hosts -%}
        {%- if host in groups[name] -%}
          {% do hosts.append("ip-" + host.replace('.','-') + ":" + mongo_port) %}
        {%- endif -%}
      {%- endfor -%}
    {%- endif -%}
  {%- endfor -%}
{%- else -%}
  {%- set hosts = mongo_cluster_members -%}
{%- endif -%}

config = {_id: '{{ mongo_repl_set }}', members: [
       {%- for host in hosts -%}
       {_id: {{ loop.index }}, host: '{{ host }}'}{% if not loop.last %},{% endif %}
       {%- endfor -%}
           ]};
rs.initiate(config)

sleep(30000)
rs.slaveOk()
printjson(rs.status())

// Check that the cluster is ok
if(!rs.status().ok) { throw 'Mongo Cluster Not Ok';}

// Check that the cluster has the right number of members
// and add them if we are the master
if(rs.isMaster().ismaster) {
    if(rs.status().members.length!={{ hosts|length }}) {
        {% for host in mongo_cluster_members %}
        rs.add({_id: {{ loop.index }}, host: '{{ host }}'});
        {% endfor %}
        sleep(30000);
        // Check status and member account, throw exception if not
        if(!rs.status().ok) { throw 'Mongo Cluster Not Ok';}
        if(rs.status().members.length!={{ hosts|length }}) {
            throw 'Could not add all members to cluster'
        }
    }
    // Now add super user to cluster
    conn = new Mongo();
    db = conn.getDB("admin");
    db.auth( '{{ MONGO_ADMIN_USER }}', '{{ MONGO_ADMIN_PASSWORD }}');

    if(db.getUser("{{ MONGO_ADMIN_USER }}") == null) {
        db.createUser(
            {
                "user": "{{ MONGO_ADMIN_USER }}",
                "pwd": "{{ MONGO_ADMIN_PASSWORD }}",
                "roles": ["root"]
            }
        );
    } else {
        db.updateUser(
            "{{ MONGO_ADMIN_USER }}",
            {
                "pwd": "{{ MONGO_ADMIN_PASSWORD }}",
                "roles": ["root"]
            }
        );
    }
}
