{# instance that runs WCFS service associated with ZODB storage  #}
{% from "instance_zodb_base" import zodb_dict  with context %}

{# q(text) returns urllib.quote_plus(text) #}
{% macro q(text) %}{{ urllib_parse.quote_plus(text) }}{% endmacro %}

{# build zurl to connect to configured ZODB #}
{% if len(zodb_dict) != 1 -%}
{%   do assert(False, ("WCFS supports only single ZODB storage", zodb_dict)) -%}
{% endif -%}

{% set db_name, zodb = zodb_dict.popitem() -%}
{% set z = zodb['storage-dict'] -%}
{% if zodb['type'] == 'zeo' -%}
{%   set zurl = ('zeo://%s?storage=%s' % (z['server'], z['storage'])) -%}
{% elif zodb['type'] == 'neo' -%}
{#   neo(s)://[credentials@]master1,master2,...,masterN/name?options #}
{#   (see https://lab.nexedi.com/kirr/neo/blob/3e13fa06/go/neo/client.go#L417) #}
{#   If 'ca' in storage-dict, ssl is true. #}
{#   (see https://lab.nexedi.com/nexedi/slapos/blob/397726e1/stack/erp5/instance-zodb-base.cfg.in#L17-21) #}
{%   if "ca" in z -%}
{#     ca=ca.crt;cert=my.crt;key=my.key  (see https://lab.nexedi.com/kirr/neo/blob/3e13fa06/go/neo/client.go#L428) #}
{%     set zurl = 'neos://ca=%s;cert=%s;key=%s@' % (q(z.pop("ca")), q(z.pop("cert")), q(z.pop("key"))) -%}
{%   else -%}
{%     set zurl = 'neo://' -%}
{%   endif -%}
{%   set zurl = ('%s%s/%s' % (zurl, z.pop('master_nodes')|replace(" ", ","), z.pop('name'))) -%}
{%   set zurl = zurl + '?' + (z | dictsort | urlencode) -%}
{% else -%}
{%   do assert(False, ("unsupported ZODB type", zodb)) -%}
{% endif -%}


[buildout]
extends = {{ template_monitor }}
parts +=
  wcfs
  wcfs-promise
  publish


[directory]
recipe = slapos.cookbook:mkdirectory
etc = ${buildout:directory}/etc
log = ${:var}/log
run = ${:var}/run
services = ${:etc}/run
service-on-watch = ${:etc}/service
srv = ${buildout:directory}/srv
tmp = ${buildout:directory}/tmp
var = ${buildout:directory}/var

[wcfs]
recipe = slapos.cookbook:wrapper
command-line = {{ bin_directory }}/wcfs serve -log_dir=${directory:log} {{ zurl }}
wrapper-path = ${directory:service-on-watch}/wcfs

[wcfs-promise]
<= monitor-promise-base
promise = check_command_execute
name = ${:_buildout_section_name_}.py
config-command = {{ bin_directory }}/wcfs status {{ zurl }}

[publish]
recipe = slapos.cookbook:publish.serialised
serving-zurl = {{ zurl }}
