#############################
#
# Instanciate nbdserver
#
#############################
[buildout]
parts =
  nbd-promise
  onetimeupload-promise
  publish-connection-information
extends = {{ template_monitor }}

{% set ipv6 = slap_configuration['ipv6-random'] -%}

[rootdirectory]
recipe = slapos.cookbook:mkdirectory
bin = ${buildout:directory}/bin
etc = ${buildout:directory}/etc
srv = ${buildout:directory}/srv
log = ${buildout:directory}/log

[basedirectory]
recipe = slapos.cookbook:mkdirectory
services = ${rootdirectory:etc}/run
watched-services = ${rootdirectory:etc}/service

[nbd-instance]
recipe = slapos.cookbook:nbdserver
ip = {{ ipv6 }}
port = 1024
image-path = ${onetimeupload-instance:image-path}
qemu-path =  {{ qemu_nbd_executable_location }}
shell-path = {{ dash_executable_location }}
# XXX TODO: Wait for the iso to be uploaded (execute_wait)
path = ${basedirectory:services}/nbdserver

[nbd-checker-bin]
recipe = slapos.recipe.template:jinja2
template = inline:#!/bin/sh
  [ ! -f ${onetimeupload-instance:image-path} ] ||
    ${buildout:executable} -c 'import socket ; socket.create_connection(("${nbd-instance:ip}","${nbd-instance:port}")).close()'
rendered = ${rootdirectory:bin}/check-nbd-running.sh

[nbd-promise]
<= monitor-promise-base
module = check_command_execute
name = nbd_promise.py
config-command = ${nbd-checker-bin:rendered}

[gen-passwd]
recipe = slapos.cookbook:generate.password
storage-path = ${rootdirectory:srv}/passwd
bytes = 24

[onetimeupload-instance]
recipe = slapos.cookbook:onetimeupload
ip = {{ ipv6 }}
port = {{ slapparameter_dict.get('otu-port', 8080) }}
image-path = ${rootdirectory:srv}/cdrom.iso
log-path = ${rootdirectory:log}/onetimeupload.log
shell-path = {{ dash_executable_location }}
onetimeupload-path = {{ onetimeupload_executable_location }}
path = ${basedirectory:watched-services}/onetimeupload
key = ${gen-passwd:passwd}

[onetimeupload-promise]
<= monitor-promise-base
module = check_port_listening
name = onetimeupload_promise.py
config-hostname = ${onetimeupload-instance:ip}
config-port = ${onetimeupload-instance:port}

[publish-connection-information]
recipe = slapos.cookbook:publish
nbd_hostname = ${nbd-instance:ip}
nbd_port = ${nbd-instance:port}
upload_url = http://[${onetimeupload-instance:ip}]:${onetimeupload-instance:port}
upload_key = ${onetimeupload-instance:key}
status_message = ${detect-if-cdrom-present:status}

[detect-if-cdrom-present]
recipe = slapos.recipe.build
init =
  import os
  options['status'] = (
    "image already uploaded, you can't upload it again"
    if os.path.isfile("${onetimeupload-instance:image-path}")
    else "WARNING: no image yet, the NBD server doesn't work")
