<% unless p("cf_networking.disable") %>
<%=
  require 'json'

  def db_param_path(name)
    "cf_networking.silk_controller.database.#{name}"
  end

  def db_param(name)
    if_p(db_param_path name) do |param|
      return param
    end.else do
      return nil
    end
  end

  def require_db_param(name)
    param = db_param name
    return param if !param.nil?

    raise "#{db_param_path name} must be specified"
  end

  def db_host
    from_property = db_param 'host'
    return from_property if !from_property.nil?

    from_link = link("database").instances[0].address
    return from_link if !from_link.nil?

    raise "must provide database link or set #{db_param_path 'host'}"
  end

  user = require_db_param 'username'
  password = require_db_param 'password'
  port = require_db_param 'port'
  name = require_db_param 'name'
  driver = require_db_param 'type'

  unless driver == 'mysql' || driver == 'postgres'
    raise "unknown driver  #{driver}"
  end

  def subnet_prefix_length
    size = p("cf_networking.subnet_prefix_length")
    if size < 1 || size > 30
      raise "'cf_networking.subnet_prefix_length' must be a value between 1-30"
    end
    size
  end

  toRender = {
    "debug_server_port" => p("cf_networking.silk_controller.debug_port"),
    "health_check_port" => p("cf_networking.silk_controller.health_check_port"),
    "listen_host" => p("cf_networking.silk_controller.listen_ip"),
    "listen_port" => p("cf_networking.silk_controller.listen_port"),
    "ca_cert_file" => "/var/vcap/jobs/silk-controller/config/certs/ca.crt",
    "server_cert_file" => "/var/vcap/jobs/silk-controller/config/certs/server.crt",
    "server_key_file" => "/var/vcap/jobs/silk-controller/config/certs/server.key",
    "network" => p("cf_networking.network"),
    "subnet_prefix_length" => subnet_prefix_length,
    "database" => {
      "type" => driver,
      "user" => user,
      "password" => password,
      "host" => db_host,
      "port" => port,
      "timeout" => p("cf_networking.silk_controller.connect_timeout_seconds"),
      "database_name" => name,
    },
    "lease_expiration_seconds" => p("cf_networking.subnet_lease_expiration_hours") * 60 * 60,
    "metron_port" => p("cf_networking.silk_controller.metron_port"),
    "staleness_threshold_seconds" => 60*60,
    "metrics_emit_seconds" => 30,
    "log_prefix" => "cfnetworking",
  }

  JSON.pretty_generate(toRender)
%>
<% end %>
