[%
# vi: ft=tt2

# Only for usage with instances setup, and only to be used on Proxy / LB hosts.
#
# Returns a list of prepared records for /etc/hosts file.
# It differentiates PRO and Carrier setups automatically and fills
# the records accordingly to the setup type.
# If the NGCP setup has no instances, script will return an empty list.

out = [];

proxy_role = 'proxy';
lb_role = 'lb';

sql_role = 'db';
nosql_role = 'db';

iface_marker = 'ha_int';

hostname = ngcp.get_hostname();
is_lb = ngcp.has_role(hostname, lb_role);
is_proxy = ngcp.has_role(hostname, proxy_role);

# if this host where the script is running, is not a Proxy/LB node, skip further execution
IF instances.defined && instances.size > 0 && (is_proxy || is_lb);

  hostnames_records_sql = [];
  hostnames_records_nosql = [];

  # get my ha ip (not a shared ip)
  argv.host = hostname;
  argv.type = iface_marker;
  PROCESS '/usr/lib/ngcp-ngcpcfg/get_all_ips_for_host';
  my_ha_ip = out.0;

  FOREACH host IN hosts.keys.sort;
    this_host_has_sql_role = ngcp.has_role(host, sql_role);
    this_host_has_nosql_role = ngcp.has_role(host, nosql_role);
    this_host_has_proxy_role = ngcp.has_role(host, proxy_role);
    this_host_has_lb_role = ngcp.has_role(host, lb_role);

    IF is_proxy && (this_host_has_sql_role || this_host_has_nosql_role);
      argv.host = host;
      argv.type = iface_marker;
      PROCESS '/usr/lib/ngcp-ngcpcfg/get_all_shared_ips_for_host';

      IF this_host_has_sql_role && out.0;
        hostnames_records_sql.push(out.0 _ ' db.central.' _ host);
      END;
      IF this_host_has_nosql_role && out.0;
        hostnames_records_nosql.push(out.0 _ ' nosql.central.' _ host);
      END;
    END;

    IF is_proxy && this_host_has_proxy_role;
      hostnames_records_sql.push(my_ha_ip _ ' db.replicatedpair.' _ host);
      hostnames_records_sql.push(my_ha_ip _ ' db.replicatedcentral.' _ host);
    END;

    IF (is_proxy && this_host_has_proxy_role) || (is_lb && this_host_has_lb_role);
      hostnames_records_nosql.push(my_ha_ip _ ' nosql.replicatedpair.' _ host);
    END;
  END;

  out = hostnames_records_nosql.merge(hostnames_records_sql);
END;

out = out.unique.sort;

-%]
