<%=
require 'yaml'

bpm = {
  "processes" => [
    { "name" => "route_registrar",
    "executable" => "/var/vcap/packages/route_registrar/bin/route-registrar",
    "env" => {},
    "args" => [
       "--configPath",
       "/var/vcap/jobs/route_registrar/config/registrar_settings.json",
       "-timeFormat",
       "rfc3339",
       "-logLevel",
       p('route_registrar.logging_level'),
     ],
    }
  ]
}

paths = []
unrestricted_volumes = []
routes = p('route_registrar.routes')
unsafe_privileged = false

routes.each do |route|
  if route['health_check']
    # valid path is /var/vcap/jobs/JOB
    matched = /(^\/var\/vcap\/jobs\/[^\/]*)\/.*/.match(route['health_check']['script_path'])
    if matched
      paths.append({ "path" => matched[1], "allow_executions" => true })
      paths.append({ "path" => matched[1].sub('jobs', 'data') })
    end

    if route['health_check']['privileged']
      unsafe_privileged = route['health_check']['privileged']
    end

    if route['health_check']['unrestricted_volumes']
      unrestricted_volumes.concat(route['health_check']['unrestricted_volumes'].map { |unrestricted_volume|
        {
          "path" => unrestricted_volume["path"],
          "writable" => unrestricted_volume["writable"] || false,
          "allow_executions" => unrestricted_volume["allow_executions"] || false,
        }
      })
    end
  end
end

if_p('route_registrar.dynamic_config_globs') do |globs|
   globs.each do |glob|
     paths.append({ "path" => File.dirname(glob), "mount_only" => true })
   end
 end

unless paths.empty?
  paths.each do |path|
    existing_path = unrestricted_volumes.find { |unrestricted_volume| unrestricted_volume['path'] == path['path'] }
    if existing_path
      existing_path.merge!(path)
    else
      unrestricted_volumes << path
    end
  end

  unsafe = {
    "unsafe" => {
      "privileged" => unsafe_privileged,
      "unrestricted_volumes" => unrestricted_volumes
    }
  }

  bpm['processes'][0].merge!(unsafe)
end

YAML.dump(bpm)
%>
